
local qidian = false
if tonumber(os.date("%w")) == 6 then
  qidian = true
end

local desc_tshu = [[
  # 无尽天书模式简介



  限1~5人与人机游玩，玩家挑战将池中所有武将，收集全部将灵，直到玩家死亡..

  房间的副将开关为体验模式开关，非体验模式一周目—————通关第5层，二周目————50层，三周目————100层。

  人越多难度越低，注：能看队友手牌噢

  请保证真人不超过房间人数一半。


  (武将重新上场时，会触发一次所有游戏开始时可触发的技能..正常来说)

  

  建议自己控制好将池，以免过于被搞心态。
  ___

  为减少服务器与客户端压力，加入了手牌与技能数上限

  当手牌数超过150张时，随机将手牌弃至50张

  当技能数超过40个时，选择至多20个技能保留

  以上每个效果每回合限生效一次
  ___

  牌堆移除【乐不思蜀】，【诸葛连弩】

  
  通过前5关每过一关都可以选择一次天书技能，后续通过5的倍数关时方可选择一次天书技能；


  获得的天书技能数达到10个时，将不会再获得新技能，仅仅只可重置技能。

  虚拟偶像死亡后可以重新召唤..

  每通过10层，每名玩家就需要从随机抽取的已击杀武将中选择一个加入公共武将库，玩家武将库更新或玩家死亡时，可以从武将库中选择一名武将重新上场。


  狂暴机制：


  A.每关的第五轮开始时（只第五轮该机制才生效），所有角色玩家弃置各自区域里的所有牌。


  B.每关的第七轮起（第七轮开始之后的每轮该机制皆生效），角色玩家在各自的回合开始时失去1点体力。




  BOSS会根据通关层数获得以下增益（X > 0 ，X的增加也会使得增益增加)：


  10X+1
  体力和体力上限增加1点


  10X+2
  回合开始时摸1张牌


  10X+3
  体力和体力上限增加1点


  10X+4
  回合结束时摸1张牌


  10X+5
  回合开始时回复1点体力


  10X+6
  体力和体力上限增加1点


  10X+7
  回合开始时摸1张牌


  10X+8
  体力和体力上限增加1点


  10X+9
  回合结束时摸1张牌


  10X
  造成伤害时，伤害值+1;获得一个随机天书技能

  

]]
local jump = function(player,num)
  local room = player.room
  local ag2 = room:getBanner("@layers") or 0
  if not num or ag2 >= num then return end
  player:broadcastSkillInvoke(table.random({"tshujl__juejing","tshujl__longhun"}))
  room:doBroadcastNotify("ShowToast", "<font color='red'>神赵直通车</font>，开始直通第 "..num.." 层！")
  room:delay(500)
  local n = num - ag2
  local m = n//10
  if m > 0 then
    room:setBanner("tshu-hp", (room:getBanner("tshu-hp") or 0) + 4*m)
    room:setBanner("tshu-damage", (room:getBanner("tshu-damage") or 0) + m)
    room:setBanner("tshu-start", (room:getBanner("tshu-start") or 0) + 2*m)
    room:setBanner("tshu-finish", (room:getBanner("tshu-finish") or 0) + 2*m)
    room:setBanner("tshu-cover", (room:getBanner("tshu-cover") or 0) + m)
    ag2 = ag2 + m*10
  end
  local y = n%10
  if y > 0 then
  for i = 1,y, 1 do
      ag2 = ag2 + 1
    if ag2 >= 10 and (ag2%10 == 1 or ag2%10 == 3 or ag2%10 == 6 or ag2%10 == 8) then
      room:setBanner("tshu-hp", (room:getBanner("tshu-hp") or 0) + 1)
    elseif ag2 >= 10 and ag2%10 == 0 then
      room:setBanner("tshu-damage", (room:getBanner("tshu-damage") or 0) + 1)
    elseif ag2 >= 10 and (ag2%10 == 2 or ag2%10 == 7) then
      room:setBanner("tshu-start", (room:getBanner("tshu-start") or 0) + 1)
    elseif  ag2 >= 10 and (ag2%10 == 4 or ag2%10 == 9) then
      room:setBanner("tshu-finish", (room:getBanner("tshu-finish") or 0) + 1)
    elseif  ag2 >= 10 and ag2%10 == 5  then
      room:setBanner("tshu-cover", (room:getBanner("tshu-cover") or 0) + 1)
    end
  end
  end
  ag2 = ag2 - 1
  room:setBanner("@layers",ag2)
  if num ~= 150 then
    room:setBanner("jump",1)
  end
end

local function laygo(player)
  local room = player.room
  local lay1 = "第99层"
  local lay2 = "第199层"
  local lay3 = "第299层"
  local lay4 = "第399层"
  local lay5 = "第499层"
  local lay6 = "第599层"
  local lay7 = "第699层"
  local lay8 = "第799层"
  local lay9 = "第899层"
  local lay10 = "第999层"
  local back = "当前层"
  local shops = {lay1,lay2,lay3,lay4,lay5,lay6,lay7,lay8,lay9,lay10,back}
  local canshops = {}
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  --已解锁层数
  local lose = all - win - 2
  local ag =  room:getBanner("@layers") or 0
  local n = (ag+2)//100
  if lose > n then
    for i = 1, 10, 1 do
      if n < i and lose >= i then
        table.insertIfNeed(canshops,shops[i])
      end
    end
  end
  table.insertIfNeed(canshops,back)
  local goug = room:askForCustomDialog(player,"神赵直通车","packages/tshu/qml/DialogChoiceBox.qml",{"神赵直通车","选择要通过 <font color='red'>神赵直通车</font> 前往的层数,使用<font color='red'>神赵直通车</font>后将无法解锁<font color='purple'>5~200层</font>的将灵：",canshops,"tshujl__zhaoyun"})
  local gou
  if goug ~= "" then
    gou = json.decode(goug)
  end
  --local gou = room:askForChoice(player,canshops,"神赵直通车","选择要通过 <font color='red'>神赵直通车</font> 前往的层数,使用<font color='red'>神赵直通车</font>后将无法解锁<font color='purple'>5~200层</font>的将灵",false,shops)
  if gou and gou ~= "当前层" then
    local num = room:getBanner("@layers")
    if gou == "第99层" then
      num = 99
    elseif gou == "第199层" then
      num = 199
    elseif gou == "第299层" then
      num = 299
    elseif gou == "第399层" then
      num = 399
    elseif gou == "第499层" then
      num = 499
    elseif gou == "第599层" then
      num = 599
    elseif gou == "第699层" then
      num = 699
    elseif gou == "第799层" then
      num = 799
    elseif gou == "第899层" then
      num = 899
    elseif gou == "第999层" then
      num = 999
    end
    jump(player,num)
  end
end
-- FIXME: Disable same convert by param or extra data
local function rm(generals, g)
  local gt = Fk.generals[g].trueName
  for i, v in ipairs(generals) do
    if Fk.generals[v].trueName == gt then
      table.remove(generals, i)
      return
    end
  end
end
local LangAI = require "packages/tshu/AI/LangAI"
local T = require "packages/tshu/record/Theorem"
local U = require "packages/utility/utility"

local tshu_getLogic = function()
  local tshu_logic = GameLogic:subclass("tshu_logic")
  ---虚拟偶像
  local ox = {"tshuox__xiaosha","tshuox__xiaojiu","tshuox__xiaotao","tshuox__xiaole","tshuox__xiaoshan"}
  --诸神
  local godboss = {"tshugod__jiaxu1","tshugod__jiaxu2","tshugod__kuafu","tshugod__shaohao","tshugod__xuannv","tshugod__hanba","tshugod__caoe","tshugod__taoshen","tshugod__hebo","tshugod__yuershen","tshugod__yanluowang"}
    --年夕兽
  local nx = {"tshunx__nwei","tshunx__nqun","tshunx__nshu","tshunx__nwu","tshunx__xwu","tshunx__xwei","tshunx__xqun","tshunx__xshu","tshunx__pucong"}
  --生肖
  local sx = {"tshusx__shu","tshusx__niu","tshusx__hu","tshusx__tu","tshusx__long","tshusx__she","tshusx__ma","tshusx__yang","tshusx__hou","tshusx__ji","tshusx__gou","tshusx__zhu"}
  --黑名单
  local black = {"emotest","mouxusheng","tshujl__zhugeguo","tshujl__lingjv","tshujl__zhouyu","tshujl__caoying","tshujl__guansuo","tshujl__nianshou","tshujl__zhaoxiang","tshujl__xiaosha","tshujl__caochun","tshulz__zuogu","tshulz__yougu","tshujl__guanyu","tshujl__zhaoyun","tshujl__nianzhugeliang","tshujl__miaolvlingqi","tshujl__nianlvbu"}
  --神
  local god = {"godcaopi","godjiaxu","godxuchu","goddengai","godzhouyu","joy__godzuoci", "godliubei","goddiaochan","godzhenji","joy__goddaxiaoqiao","godhuatuo","joy__goddianwei","godzhaoyun", "godganning","godguanyu","godcaocao", "godtaishici","godlvbu","godlvmeng","godzhangliao","godsunquan","godmachao","godzhangjiao","godjiangwei","godxunyu","godsunce","godguojia","godluxun","godsimayi","godzhugeliang"}
  --保留印记
  local nmark = {"tshujl__miaolvlingqi","@tshu_lv","@deputyHp","tongling","tshujl__chuangshi_choose","@[tshu__tianshu]","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@&tshu__jlmark","wangzhe","juejie","chaoyuan","shengti","shuangsheng"}
  --黑名单卡牌
  local blacklist = {"crossbow","indulgence","wd_rice","diy_restart"}
  for _, g in ipairs(god) do
    for _, n in ipairs(Fk:getSameGenerals(g)) do
      table.insertIfNeed(god,n)
    end
  end

  function tshu_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord","renegade","rebel",},
      { "lord","renegade","rebel", "rebel",},
      {"lord", "loyalist", "renegade","rebel", "rebel"},
      { "lord","loyalist", "renegade", "rebel", "rebel", "rebel" },
      { "lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel" },
      { "lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel","rebel"},
      { "lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel","rebel","rebel"},
      { "lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel","rebel","rebel","rebel"},
    }
  end

  function tshu_logic:prepareForStart()
    local room = self.room
    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" and trig.name ~= "tenyear_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
     local sk = {"tshu__fpj4","tshu__fzb"}
     if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
      table.insertIfNeed(sk,"tshu__qdian")
     end
    for _, name in ipairs(sk) do
      local s = Fk.skills[name]
      if s:isInstanceOf(TriggerSkill) and RoomInstance then
        self:addTriggerSkill(s)
      end
      if s:isInstanceOf(StatusSkill) then
        room.status_skills[s.class] = room.status_skills[s.class] or {}
        table.insertIfNeed(room.status_skills[s.class], s)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end


  function tshu_logic:prepareDrawPile()
    local room = self.room
    local seed = math.random(2 << 32 - 1)
    local allCardIds = Fk:getAllCardIds()
    
    local whitelist = {}
    for i = #allCardIds, 1, -1 do
      local card = Fk:getCardById(allCardIds[i])
      local name = card.name
      if (card.is_derived and not table.contains(whitelist, name)) or table.contains(blacklist, name) then
        local id = allCardIds[i]
        table.removeOne(allCardIds, id)
        table.insert(room.void, id)
        room:setCardArea(id, Card.Void, nil)
      end
    end
  
    table.shuffle(allCardIds)
    room.draw_pile = allCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end
  
  function tshu_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n-2]
    table.shuffle(roles)

    local bots_t = {}
    local players_t = {}
    for i = 1, n do
      local p = room.players[i]
      if p.id < 0 then
        table.insert(bots_t,{p.id,i})
      end
      if p.id > 0 then
        table.insert(players_t,{p.id,i})
      end
    end

    if #bots_t >= 1 then
      local lord_t = table.random(players_t)
      local lord_player = room.players[lord_t[2]]
      lord_player.role = "lord"
      lord_player.role_shown = true
      room:broadcastProperty(lord_player, "role")
      local renegade = true
      for i = 1, n do
        local p = room.players[i]
        if p.role ~= "lord" then
          if p.id < 0 then
             p.role = "rebel"
          else
            p.role = "loyalist"
          end
          p.role_shown = true
          room:notifyProperty(p, p, "role")
        end
      end
    else
      --默认主反模式
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        if p.role == "lord" then
          p.role_shown = true
          room:broadcastProperty(p, "role")
        else
          room:notifyProperty(p, p, "role")
        end
      end
    end
    local lord = {}
    local rebel = {}
    for _, p in ipairs(room.players) do
      if p.role == "loyalist" or p.role == "lord" then
        table.insert(lord,p)
      elseif p.role == "rebel" then
        table.insert(rebel,p)
      end
    end
    for _, p in ipairs(lord) do
      for _, p2 in ipairs(lord) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end
    for _, p in ipairs(rebel) do
      for _, p2 in ipairs(rebel) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end
  end
  --[[
   function tshu_logic:PVE()
    local room = self.room ---@type Room
    local tar = {}
    for _, p in ipairs(room.players) do
      if p.role == "lord" or p.role == "loyalist" then
        table.insertIfNeed(tar,p.id)
      end
    end
    for _, p in ipairs(tar) do
      local choices = {"pvebuff1","pvebuff2","pvebuff3"}
      p.request_data = json.encode({choices, choices, self.name, "#pvebuff-choice"})
    end
    room:notifyMoveFocus(room.alive_players, self.name)
    room:doBroadcastRequest("AskForChoice", tar)

    for _, p in ipairs(tar) do
      local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        p.client_reply = "pvebuff2"
        choice = "pvebuff2"
      end
      room:sendLog{
        type = "#tshu__buff-quest",
        from = p.id,
        arg = choice,
      }
      local buff1,buff2,buff3,buff4 = false,false,false,false
      if choice == "pvebuff1" then
        buff1 = true
        buff2 = true
      elseif choice == "pvebuff2" then
        buff1 = true
        buff3 = true
      elseif choice == "pvebuff3" then
        buff3 = true
        buff4 = true
      end

      if buff1 then
        local m = room:getBanner(fk.DrawNCards) or {}
        table.insertIfNeed(m,p.id)
        room:setBanner(fk.DrawNCards,p.id)
      end
      if buff2 then
        local m = room:getBanner(fk.DamageCaused) or {}
        table.insertIfNeed(m,p.id)
        room:setBanner(fk.DamageCaused,p.id)
      end
      if buff3 then
        local m = room:getBanner(fk.TurnStart) or {}
        table.insertIfNeed(m,p.id)
        room:setBanner(fk.TurnStart,p.id)
      end
      if buff4 then
        local m = room:getBanner(fk.DamageInflicted) or {}
        table.insertIfNeed(m,p.id)
        room:setBanner(fk.DamageInflicted,p.id)
      end
    end
  end
]]
  --选将
  function tshu_logic:chooseGenerals()
    local room = self.room ---@type Room
    local n = room.settings.generalNum
    local m = room.settings.enableDeputy and 2 or 1
    local gpile = table.simpleClone(room.general_pile)
    local black2 = {"jbsao__wuyaowang","ty__tengfanglan","jbs_sairen","luyi","dingfuren","zuoci","os__zhaoxiang","zhaoxiang","ol_ex__zuoci","buqun__ailing"}
    for _, g in ipairs(gpile) do
      if Fk.generals[g].package.extensionName == "tshu" or table.contains(black2,g) or table.contains(god,g)  then
        table.removeOne(room.general_pile,g)
      end
    end
    --[[
    for _, g in ipairs(room.general_pile) do
      if Fk.generals[g].package.extensionName == "ycy" then
        table.removeOne(room.general_pile,g)
      end
    end]]
    local lord = {}
    local rebel = {}
    local ren = {}
    local j
    local r
    for _, p in ipairs(room.players) do
      if p.role == "loyalist"   then
        table.insert(lord,p)
      elseif p.role == "lord" then
        table.insert(lord,p)
        j = p
      elseif p.role == "rebel" then
        table.insert(rebel,p)
      end
    end
    room.current = j

    if tonumber(os.date("%w")) == 6 then
      room:setBanner("@[:]sday_qdian","sday_qdian")
    end
    
    --PVEbuff
    for _, p in ipairs(lord) do
      local choices = {"pvebuff1","pvebuff2","pvebuff3"}
      p.request_data = json.encode({choices, choices, "tshu__buff", "#pvebuff-choice",true})
    end
    room:notifyMoveFocus(room.alive_players,"tshu__buff")
    room:doBroadcastRequest("AskForChoice", lord)

    for _, p in ipairs(lord) do
      local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        p.client_reply = "pvebuff2"
        choice = "pvebuff2"
      end
      room:sendLog{
        type = "#tshu__buff-quest",
        from = p.id,
        arg = choice,
      }
      if choice == "pvebuff1" then
        room:setPlayerMark(p,"tshu__buff1",1)
        room:setPlayerMark(p,"tshu__buff2",1)
      elseif choice == "pvebuff2" then
        room:setPlayerMark(p,"tshu__buff1",1)
        room:setPlayerMark(p,"tshu__buff3",1)
      elseif choice == "pvebuff3" then
        room:setPlayerMark(p,"tshu__buff3",1)
        room:setPlayerMark(p,"tshu__buff4",1)
      end
    end

    --将灵
    local jlmark = {"tshujl__zhugeguo","tshujl__lingjv","tshujl__zhouyu"}
    if  not room.settings.enableDeputy then
        table.insertIfNeed(jlmark,"tshujl__zhaoxiang")
    end
    for _, p in ipairs(lord) do
      local all = p._splayer:getGameData():at(0)
      local win = p._splayer:getGameData():at(1)
      local lose = all - win
      --room:setPlayerMark(p,"tshu__win",win)
      if  win >= 1 then
        table.insertIfNeed(jlmark,"tshujl__caoying")
      end
      if  win >= 2 then
        table.insertIfNeed(jlmark,"tshujl__guansuo")
        table.insertIfNeed(jlmark,"tshujl__zhouyi")
      end
      if  win >= 3 then
        table.insertIfNeed(jlmark,"tshujl__caochun")
      end
      if  win >= 4 then
        table.insertIfNeed(jlmark,"tshujl__nianzhugeliang")
      end
      if  win >= 5 then
        table.insertIfNeed(jlmark,"tshujl__miaolvlingqi")
        table.insertIfNeed(jlmark,"tshujl__nianlvbu")
      end
      if lose >= 1 then
        table.insertIfNeed(jlmark,"tshujl__nianshou")
      end
      if lose >= 2 then
        table.insertIfNeed(jlmark,"tshujl__zhaoyun")
      end
    end
    room:setBanner("@&tshu__jl",jlmark)
    for _, p in ipairs(lord) do
      local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
      local all = p._splayer:getGameData():at(0)
      local win = p._splayer:getGameData():at(1)
      local lose = all - win
      if  win < 1 then
        table.removeOne(jl,"tshujl__caoying")
      end
      if  win < 2 then
        table.removeOne(jl,"tshujl__guansuo")
        table.removeOne(jl,"tshujl__zhouyi")
      end
      if  win < 3 then
        table.removeOne(jl,"tshujl__caochun")
      end
      if  win < 4 then
        table.removeOne(jl,"tshujl__nianzhugeliang")
      end
      if  win < 5 then
        table.removeOne(jl,"tshujl__miaolvlingqi")
        table.removeOne(jl,"tshujl__nianlvbu")
      end
      if  lose < 1 then
        table.removeOne(jl,"tshujl__nianshou")
      end
      if  lose < 2 then
        table.removeOne(jl,"tshujl__zhaoyun")
      end
      local skills = {}
      for _, s in ipairs(jl) do
        room:setPlayerMark(p,s,0)
        if s == "tshujl__nianzhugeliang" then
          table.insert(skills,{"tshujl__nianzhuge_choice"})
        elseif s == "tshujl__miaolvlingqi" then
          table.insert(skills,{"tshujl__miaolvlingqi_choice"})
        elseif s == "tshujl__nianlvbu" then
          table.insert(skills,{"tshujl__nianlvbu_choice"})
        else
          table.insert(skills,{s})
        end
      end
  
  p.request_data = json.encode({
    path = "packages/tshu/qml/ChooseGeneralSkillsBox.qml",
    data = {
      jl,skills, 1, 1, "#jl-choice", false
    },
  })
  p.default_reply = table.random(skills)
  end
  room:notifyMoveFocus(lord, "选择将灵")
  room:doBroadcastRequest("CustomDialog", lord)
    
  for _, p in ipairs(lord) do
    local j = p.reply_ready and json.decode(p.client_reply) or p.default_reply--json.decode(result)
    local choice = table.concat(j)
    if table.concat(j) == "tshujl__nianzhuge_choice" then
      choice = "tshujl__nianzhugeliang"
    elseif table.concat(j) == "tshujl__nianlvbu_choice" then
      choice = "tshujl__nianlvbu"
    elseif table.concat(j) == "tshujl__miaolvlingqi_choice" then
      choice = "tshujl__miaolvlingqi"
    end
    room:notifySkillInvoked(p,choice,"drawcard")
    for _, s in ipairs(Fk.generals[choice].skills) do
      p:broadcastSkillInvoke(s.name)
      break
    end
    room:setPlayerMark(p,choice,1)
    room:setPlayerMark(p,"@&tshu__jlmark",{choice})
    room:handleAddLoseSkills(p,"tshu__changejl&",nil)
    --room:handleAddLoseSkills(p,"tshu__ice&",nil)
    --room:handleAddLoseSkills(p,"tshu__store&",nil)
    p.default_reply = ""
    end

    for _, p in ipairs(lord) do
      local all = p._splayer:getGameData():at(0)
      local win = p._splayer:getGameData():at(1)
      local lose = all - win
      if lose >= 2 then
        laygo(p)
      end
    end
    --继续选将
    for _, p in ipairs(rebel) do
      local gens = room:getNGenerals(1)
      p.request_data = json.encode({ gens, 1 })
      p.default_reply = gens[1]
    end
    for _, p in ipairs(lord) do
      local gens = room:getNGenerals(n)
      p.request_data = json.encode({ gens, 1 })
      p.default_reply = gens[1]
      room:returnToGeneralPile(gens)
    end
    room:doBroadcastNotify("ShowToast", Fk:translate("tshu choose general"))
    room:notifyMoveFocus(lord, "选择武将")
    room:doBroadcastRequest("AskForGeneral", room.players)
    for _, p in ipairs(room.players) do
      if p.general == "" and p.reply_ready then
        local general = json.decode(p.client_reply)[1]
        --[[
        if p.role ~= "renegade" and table.contains(ox,general) then
          general = room:getNGenerals(1)[1]
        end]]
        room:setPlayerGeneral(p, general, true, true)
      else
        room:setPlayerGeneral(p, p.default_reply, true, true)
      end
      p.default_reply = ""
    end
    local mark = {}

    for _, p in ipairs(room.players) do
      --[[
      if p.role ~= "renegade" and table.contains(ox,p.general) then
        p.general = room:getNGenerals(1)[1]
      end]]
      room:broadcastProperty(p, "role")
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
      table.removeOne(room.general_pile,p.general)
      if p.role ~= "renegade" then
        table.insertIfNeed(mark,p.general)
      end
    end
    room:setBanner("@&Allgenerals", mark)
    room:setBanner("@&godboss",{})
    room:setBanner("@&GetGenerals",{})
    room:askForChooseKingdom(lord)
    if  room.settings.enableDeputy then
      room:setBanner("@@easy",1)
    end
    --room:setTag("SkipNormalDeathProcess", true)
    
  end

  function tshu_logic:configureAI()
    for _, p in ipairs(self.room.players) do
      if p.id < 0 then
        p.ai = nil
        p.ai = LangAI:new(p)
      end
    end
  end

  return tshu_logic
end


Fk:addQmlMark{
  name = "tshu__tianshu",
  qml_path = "packages/tshu/qml/Skillpool",
  how_to_show = function(name, value, p)
    -- FIXME: 神秘bug导致value可能为空串有待排查
    if type(value) == "table" then 
      return  tostring(#value)
    end
    return ""
  end,
 
}

local function Buddy(room)
  local lord = {}
    local rebel = {}
    for _, p in ipairs(room.players) do
      if p.role == "loyalist" or p.role == "lord" or p.role == "renegade" then
        table.insert(lord,p)
      elseif p.role == "rebel" then
        table.insert(rebel,p)
      end
    end
    for _, p in ipairs(lord) do
      for _, p2 in ipairs(lord) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end
    for _, p in ipairs(rebel) do
      for _, p2 in ipairs(rebel) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end
end

--调整座位
local function moveSeats(room)
    local targets = {}
    for _, p in ipairs(room.players) do
      if p.role == "lord" then
        table.insertIfNeed(targets,p)
      end
    end
    for _, p in ipairs(room.players) do
      if p.role == "loyalist" then
        table.insertIfNeed(targets,p)
      end
    end
    for _, p in ipairs(room.players) do
      if p.role == "renegade" then
        table.insertIfNeed(targets,p)
      end
    end
    for _, p in ipairs(room.players) do
      if p.role == "rebel" then
        table.insertIfNeed(targets,p)
      end
    end
      
    room.players = targets
    local player_circle = {}
    for i = 1, #room.players do
      room.players[i].seat = i
      table.insert(player_circle, room.players[i].id)
    end
    for i = 1, #room.players - 1 do
      room.players[i].next = room.players[i + 1]
    end
    room.players[#room.players].next = room.players[1]
    room:doBroadcastNotify("ArrangeSeats", json.encode(player_circle))
end

--游戏开始时机技能
local function restart(player)
  local skills = {}
  for _, s in ipairs(Fk.generals[player.general]:getSkillNameList()) do
    local s2 = Fk.skills[s]
    table.insertIfNeed(skills,s2)
    for _, s3 in ipairs(s2.related_skills) do
      table.insertIfNeed(skills,s3)
    end
  end
  if player.deputyGeneral and player.deputyGeneral ~= "" then
    for _, s in ipairs(Fk.generals[player.deputyGeneral]:getSkillNameList()) do
      local s2 = Fk.skills[s]
      table.insertIfNeed(skills,s2)
      for _, s3 in ipairs(s2.related_skills) do
        table.insertIfNeed(skills,s3)
      end
    end
  end
  local mark = player:getTableMark("@[tshu__tianshu]")
  if #mark > 0 then
    for _, s in ipairs(mark) do
      local s2 = Fk.skills[s]
      table.insertIfNeed(skills,s2)
      for _, s3 in ipairs(s2.related_skills) do
        table.insertIfNeed(skills,s3)
      end
    end
  end
  for _, s in ipairs(skills) do
    if s:isInstanceOf(TriggerSkill) and type(s.events) == "table" and (table.contains(s.events,fk.GameStart) or table.contains(s.events, fk.GamePrepared)) then
      local events = {fk.GamePrepared, fk.GameStart}
      for i = #events, 1, -1 do
        if not table.contains(s.events, events[i]) then
          table.remove(events, i)
        end
      end
      for _, e in ipairs(events) do
        if s:triggerable(e, player, player, nil) then
          s:trigger(e, player, player, nil)
        end
      end
    end
  end
end

local canreward
--[[
--摸牌
local function drawInit(room, player, n)
  -- TODO: need a new function to call the UI
  local cardIds = room:getNCards(n)
  player:addCards(Player.Hand, cardIds)
  for _, id in ipairs(cardIds) do
    Fk:filterCard(id, player)
  end
  local move_to_notify = {}   ---@type CardsMoveStruct
  move_to_notify.toArea = Card.PlayerHand
  move_to_notify.to = player.id
  move_to_notify.moveInfo = {}
  move_to_notify.moveReason = fk.ReasonDraw
  for _, id in ipairs(cardIds) do
    table.insert(move_to_notify.moveInfo,
    { cardId = id, fromArea = Card.DrawPile })
  end
  room:notifyMoveCards(nil, {move_to_notify})

  for _, id in ipairs(cardIds) do
    room:setCardArea(id, Card.PlayerHand, player.id)
  end
end
]]
--小天书
local function tianshu1(room, player, n,m)
  local mark = player:getTableMark("@[tshu__tianshu]")
  local function filterfuc(skill)
    local str = Fk:translate(":"..skill.name)
    return not skill.lordSkill and not table.contains(player.player_skills,skill) and #skill.attachedKingdom == 0 and skill.frequency < Skill.Limited
    and not (string.find(str, "阵营") or string.find(str, "被动") or string.find(str, "超元气必杀") or 
    string.find(str, "元气") )
  end
    local gskills=T.getskillfrompool(player,room,filterfuc,30,m,n)--选取技能
  for _, sk in ipairs({gskills}) do
    table.forEach(sk, function(s)  table.insertIfNeed(mark,s) end)
  end
  room:setPlayerMark(player,"@[tshu__tianshu]",mark)

end
--大天书
local function tianshu2(room, player, n,m)
  local mark = player:getTableMark("@[tshu__tianshu]")
  local function filterfuc(skill)
    local str = Fk:translate(":"..skill.name)
    return not skill.lordSkill and not table.contains(player.player_skills,skill) and #skill.attachedKingdom == 0 
    and (skill.frequency == Skill.Limited or skill.frequency == Skill.Wake)
    and not (string.find(str, "阵营") or string.find(str, "被动") or string.find(str, "超元气必杀") or 
    string.find(str, "元气") )
  end
    local gskills=T.getskillfrompool(player,room,filterfuc,30,m,n)--选取技能
  for _, sk in ipairs({gskills}) do
    table.forEach(sk, function(s)  table.insertIfNeed(mark,s) end)
  end
  room:setPlayerMark(player,"@[tshu__tianshu]",mark)

end
--移除天书
local function  remove(room,player,n)
  local mark = player:getTableMark("@[tshu__tianshu]")
  if #mark < 1 then return end
  local gskills = T.choosemarkskill(player,mark,room,1)
  if #gskills>0 then
    for _, sk in ipairs({gskills}) do
      table.forEach(sk, function(s)  table.removeOne(mark,s) end)
    end
    room:handleAddLoseSkills(player, "-"..table.concat(gskills, "|-"), nil)
    room:setPlayerMark(player,"@[tshu__tianshu]",mark)
  end
end
--临时技能 
local function lshi1(room, player, n,m)
  local function filterfuc(skill)
    local str = Fk:translate(":"..skill.name)
    return not skill.lordSkill and not table.contains(player.player_skills,skill) and #skill.attachedKingdom == 0 and skill.frequency < Skill.Limited
    and not (string.find(str, "阵营") or string.find(str, "被动") or string.find(str, "超元气必杀") or 
    string.find(str, "元气") )
  end
  local gskills=T.getskillfrompool2(player,room,filterfuc,30,m,n)--选取技能
end
--交换公共技能库
local function gongskill(player)
  local room = player.room
  if not room:getBanner("@[:]tshu__gongskill") then return end
  local skill = room:getBanner("@[:]tshu__gongskill")
  local mark = player:getTableMark("@[tshu__tianshu]")
  local gskills = T.choosemarkskill(player,mark,room,1)
  local ox
  for _, p in ipairs(room.players) do
    if p.role == "renegade" then
      ox = p
    end
  end
  if #gskills>0 then
    for _, sk in ipairs({gskills}) do
      table.forEach(sk, function(s)  table.removeOne(mark,s) end)
    end
    for _, sk in ipairs({gskills}) do
      table.forEach(sk, function(s)  room:setBanner("@[:]tshu__gongskill",s) end)
    end
    room:handleAddLoseSkills(player, "-"..table.concat(gskills, "|-"), nil)
    room:handleAddLoseSkills(player, skill, nil)
    room:handleAddLoseSkills(ox, "-"..skill, nil)
    room:handleAddLoseSkills(ox,table.concat(gskills, "|"), nil)
    table.insertIfNeed(mark,skill)
    
    room:setPlayerMark(player,"@[tshu__tianshu]",mark)
  end
end
--选择获得武将
local function addGenerals(player)
  local room = player.room
  
  local m = room.settings.generalNum
  local All = table.simpleClone(room:getBanner("@&Allgenerals"))
  local Get = table.simpleClone(room:getBanner("@&GetGenerals"))
  local Get2 = table.simpleClone(Get)
  for _, p in ipairs(room.alive_players) do
    if p.role == "lord" or p.role == "loyalist" then
      table.insertIfNeed(Get2,p.general)
    end
  end
  if Get2 then 
    for _, j in ipairs(All) do
      if table.contains(Get2,j) then
        table.removeOne(All,j)
      end
    end
    local toAll = table.random(All,m)
    if #toAll == 0 then return end
    room:doBroadcastNotify("ShowToast", Fk:translate("#tshu__get"))
    ---选择一个击败武将加入所持武将库
    local gg = room:askForGeneral(player,toAll,1,false)
    --判断是否为选项内武将
    if not table.contains(toAll,gg) then
      gg = table.random(toAll)
    end
    if gg and gg ~= "" and gg[1] and gg[1] ~= "" then
      table.insertIfNeed(Get,gg)
      room:setBanner("@&GetGenerals",Get)
      for _, p in ipairs(room.alive_players) do
        if not p:hasSkill("tshu__change&") and (p.role == "lord" or p.role == "loyalist") then
          room:handleAddLoseSkills(p,"tshu__change&",nil,true)
        end
      end
    end
  end
  for _, p in ipairs(room.players) do
    local gens = table.simpleClone(room:getBanner("@&GetGenerals"))
    if   #gens < 1 then break end
    if gens and #gens > 0 and (p.role == "lord" or p.role == "loyalist") and p.dead and room:askForChoice(p,{"放弃","复活"},"复活",nil,true) == "复活" then
      room:doBroadcastNotify("ShowToast","从所持武将库中选择一个武将复活")
      local g = room:askForGeneral(p,gens,1,false)
      if not table.contains(gens,g) then
        g = table.random(gens)
      end
      if g and g ~= "" and g[1]  and g[1] ~= "" then
      room:setPlayerMark(p,"tshujl__matai",0)
        local deputyHp = p:getMark("@deputyHp")
        local mark = p:getTableMark("@[tshu__tianshu]")
        local noto_rm = table.filter(p.player_skills, function(s)
          return not s.attached_equip and s.name ~= "tshu__change&" and not table.contains(mark,s.name) and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
        end)
        room:handleAddLoseSkills(p, table.concat(table.map(noto_rm, function(s) return "-" .. s.name end), "|"), nil, true)
        --补技能
      for _, s in ipairs(mark) do
        if not p:hasSkill(s) then
          room:handleAddLoseSkills(p,s,nil,true)
        end
      end
      if p.deputyGeneral ~= "" then
        if #Fk.generals[p.deputyGeneral].skills > 0 then
            for _,s in ipairs(Fk.generals[p.deputyGeneral].skills) do
            room:handleAddLoseSkills(p,s.name,nil,true)
            end
        end
        if #Fk.generals[p.deputyGeneral].other_skills > 0 then
            for _,s in ipairs(Fk.generals[p.deputyGeneral].other_skills) do
            room:handleAddLoseSkills(p,s,nil,true)
            end
        end
      end
      room:resumePlayerArea(p, p.sealedSlots)
    
      table.removeOne(gens,g)
      room:setBanner("@&GetGenerals",gens)
      room:broadcastPlaySound("./packages/shzl/audio/skill/niepan2")
      room:changeHero(p, g, false, false, true,true)
      room:revivePlayer(p, false)
      room:setPlayerProperty(p, "kingdom", Fk.generals[g].kingdom)
      room:askForChooseKingdom({p})
      room:broadcastProperty(P, "kingdom")
      room:setPlayerProperty(p, "hp", Fk.generals[g].hp)
      room:setPlayerMark(p,"@deputyHp",deputyHp)
      --drawInit(room,p,5)
      p:drawCards(5)
      restart(p)
      
    end
    end
  end
end
--交换武将
local function changeGeneral(room)
  for _, p in ipairs(room.players) do
    local gens = table.simpleClone(room:getBanner("@&GetGenerals"))
    if   #gens < 1 then break end
    local lo = 0
    for _, p2 in ipairs(room.alive_players) do
      if p2.role == "lord" or p2.role == "loyalist" then
        lo = lo + 1
      end
    end
    if gens and #gens > 0 and (p.role == "lord" or p.role == "loyalist") and p.dead and (lo == 0 or room:askForChoice(p,{"放弃","复活"},"复活",nil,true) == "复活") then
      room:doBroadcastNotify("ShowToast","从所持武将库中选择一个武将复活")
      local g = room:askForGeneral(p,gens,1,false)
      if not table.contains(gens,g) then
        g = table.random(gens)
      end
      if g and g ~= "" and g[1]  and g[1] ~= "" then
        local deputyHp = p:getMark("@deputyHp")
        room:setPlayerMark(p,"tshujl__matai",0)
        local mark = p:getTableMark("@[tshu__tianshu]")
        local noto_rm = table.filter(p.player_skills, function(s)
          return not s.attached_equip and s.name ~= "tshu__change&" and not table.contains(mark,s.name) and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
        end)
        room:handleAddLoseSkills(p, table.concat(table.map(noto_rm, function(s) return "-" .. s.name end), "|"), nil, true)
        --补技能
      for _, s in ipairs(mark) do
        if not p:hasSkill(s) then
          room:handleAddLoseSkills(p,s,nil,true)
        end
      end
      if p.deputyGeneral ~= "" then
        if #Fk.generals[p.deputyGeneral].skills > 0 then
            for _,s in ipairs(Fk.generals[p.deputyGeneral].skills) do
            room:handleAddLoseSkills(p,s.name,nil,true)
            end
        end
        if #Fk.generals[p.deputyGeneral].other_skills > 0 then
            for _,s in ipairs(Fk.generals[p.deputyGeneral].other_skills) do
            room:handleAddLoseSkills(p,s,nil,true)
            end
        end
      end
      room:resumePlayerArea(p, p.sealedSlots)
      p:reset()
      table.removeOne(gens,g)
      room:setBanner("@&GetGenerals",gens)
      room:broadcastPlaySound("./packages/shzl/audio/skill/niepan2")
      room:changeHero(p, g, false, false, true,true)
      room:revivePlayer(p, false)
      room:setPlayerProperty(p, "kingdom", Fk.generals[g].kingdom)
      room:askForChooseKingdom({p})
      room:broadcastProperty(p, "kingdom")
      room:setPlayerProperty(p, "hp", Fk.generals[g].hp)
      room:setPlayerMark(p,"@deputyHp",deputyHp)
      --drawInit(room,p,5)
      p:drawCards(5)
      restart(p)
      
    end
    end
  end
end


--年兽
local function nianshou(room,p)
  local self = room
  if not self.game_started then return end
      local id = p.id
      local general = p.general
      local mode = self.settings.gameMode

      if p.id > 0 then
        local all = p._splayer:getGameData():at(0)
        local win = p._splayer:getGameData():at(1)
        local lose = all - win
        if p.role == "lord" or p.role == "loyalist" then
            if  lose == 0  then
              self.room:updateWinRate(id, general, mode, 2, p.dead)
            end
        end
  end
end
--神赵云
local function zhaoyun(room,p)
  local self = room
  if not self.game_started then return end
      local id = p.id
      local general = p.general
      local mode = self.settings.gameMode

      if p.id > 0 then
        local all = p._splayer:getGameData():at(0)
        local win = p._splayer:getGameData():at(1)
        local lose = all - win
        if p.role == "lord" or p.role == "loyalist" then
            if  lose == 1  then
              self.room:updateWinRate(id, general, mode, 2, p.dead)
            end
        end
  end
end

local function nianzhuge(room,p)
  local self = room
  if not self.game_started then return end
  local ag = room:getBanner("@layers") or 0
  local id = p.id
  local general = p.general
  local mode = self.settings.gameMode
      if p.id > 0 then
        local win = p._splayer:getGameData():at(1)
         if  win == 3  then
            self.room:updateWinRate(id, general, mode, 1, p.dead)
         end
      end
end

local function lvbu(room,p)
  local self = room
  if not self.game_started then return end
  local ag = room:getBanner("@layers") or 0
  local id = p.id
  local general = p.general
  local mode = self.settings.gameMode
      if p.id > 0 then
        local win = p._splayer:getGameData():at(1)
         if  win == 4  then
            self.room:updateWinRate(id, general, mode, 1, p.dead)
         end
      end
end
--超级盲盒
local function random2(room,player,qd)
  --触发一次扶汉，触发一次离宫，获得N个天书技能，选择移除N个天书技能，移除所有标记和记录+重新触发一次游戏开始时技能，
  --弃置区域所有牌，获得神张飞标记，获得【蛊惑】【崩坏】,获得一个副将,增加击杀进度，清除负面技，进行9~18次闪电判定——存活即可开N次盲盒
  local r = math.random(1,100)
  if qd then
    for i = 1, 99, 1 do
      if r > 25 and r <= 55 then
        r = math.random(1,99)
      else
        break
      end
    end
    room:doBroadcastNotify("ShowToast", "庆典日！！！")
  end
  if r <= 5 then
    local rh = false
    if player:usedSkillTimes("ty__fuhan", Player.HistoryGame) == 0 then
      rh = true
    end
    local fuhan = Fk.skills["ty__fuhan"]
    room:doBroadcastNotify("ShowToast", "超级盲盒：发动一次【扶汉】！")
    room:useSkill(player, fuhan, function()
      return fuhan:use(fk.TurnStart, player, player)
    end)
    if rh then
      player:setSkillUseHistory("ty__fuhan", 0, Player.HistoryGame)
    end
  elseif r <= 10 then
    local rh = false
    if player:usedSkillTimes("ligong", Player.HistoryGame) == 0 then
      rh = true
    end
    local fuhan = Fk.skills["ligong"]
    room:doBroadcastNotify("ShowToast", "超级盲盒：发动一次【离宫】！")
    room:useSkill(player, fuhan, function()
      return fuhan:use(fk.EventPhaseStart, player, player)
    end)
    if rh then
      player:setSkillUseHistory("ligong", 0, Player.HistoryGame)
    end
  elseif r <= 20 then
    local n = math.random(2,4)
    room:doBroadcastNotify("ShowToast", "超级盲盒：获得"..n.."个天书技能！")
    tianshu1(room,player,n,n*5)
  elseif r <= 25 then
    room:broadcastPlaySound("./packages/shzl/audio/skill/niepan2")
    room:doBroadcastNotify("ShowToast", "重生！！！")
    local deputyHp = player:getMark("@deputyHp")
    player:setCardUseHistory("")
    player:setSkillUseHistory("")
    local mark = player:getTableMark("@[tshu__tianshu]")
    local nmark = {"tshujl__miaolvlingqi","@tshu_lv","@deputyHp","tongling","wangzhe","juejie","chaoyuan","shengti","shuangsheng","tshujl__chuangshi_choose","@[tshu__tianshu]","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@&tshu__jlmark","tshujl__nianzhugeliang","tshujl__miaolvlingqi"}
    local jl = room:getBanner("@&tshu__jl")
    table.insertTable(nmark,jl)
    for name, _ in pairs(player.mark) do
      if not table.contains(nmark,name) then
        room:setPlayerMark(player, name, 0)
      end
    end
    player:clearPiles()
    player:reset()
    --补技能
    for _, s in ipairs(mark) do
      if not player:hasSkill(s) then
        room:handleAddLoseSkills(player,s,nil,true)
      end
    end
    room:resumePlayerArea(player, player.sealedSlots)
    room:revivePlayer(player, false)
    restart(player)
    room:setPlayerMark(player,"@deputyHp",deputyHp)
  elseif r <= 35 then
    room:doBroadcastNotify("ShowToast", "超级盲盒：弃置所有区域内的所有牌。")
    player:throwAllCards("hej")
    player:throwAllCards("e")
    player:throwAllCards("h")
    player:throwAllCards("j")
    room:addPlayerMark(player,"manghe_lose-phase",1)
  elseif r <= 45 then
    local m = math.random(1,3)
    room:doBroadcastNotify("ShowToast", "超级盲盒：奖励你"..m.."次来自神的裁决。")
    room:addPlayerMark(player,"manghe_lose-phase",1)
    for i = 1,m do
      if math.random(1,2) == 1 then
        room:broadcastPlaySound("./packages/tenyear/audio/skill/shencai1")
      else
        room:broadcastPlaySound("./packages/tenyear/audio/skill/shencai2")
      end
      local data = {
        who = player,
        reason = "shencai",
        pattern = ".",
        extra_data = {shencaiSource = player}
      }
      room:judge(data)
      local result = {}
      if table.contains({"peach", "analeptic", "silver_lion", "god_salvation", "celestial_calabash"}, data.card.trueName) then
        table.insert(result, "@@shencai_chi")
      end
      if data.card.sub_type == Card.SubtypeWeapon or data.card.name == "collateral" then
        table.insert(result, "@@shencai_zhang")
      end
      if table.contains({"savage_assault", "archery_attack", "duel", "spear", "eight_diagram", "raid_and_frontal_attack"}, data.card.trueName) then
        table.insert(result, "@@shencai_tu")
      end
      if data.card.sub_type == Card.SubtypeDefensiveRide or data.card.sub_type == Card.SubtypeOffensiveRide or
      table.contains({"snatch", "supply_shortage", "chasing_near"}, data.card.trueName) then
        table.insert(result, "@@shencai_liu")
      end
      if #result == 0 then
        table.insert(result, "@shencai_si")
      end
      if result[1] ~= "@shencai_si" then
        for _, mark in ipairs({"@@shencai_chi", "@@shencai_zhang", "@@shencai_tu", "@@shencai_liu"}) do
          room:setPlayerMark(data.who, mark, 0)
        end
      end
      for _, mark in ipairs(result) do
        room:addPlayerMark(data.who, mark, 1)
        if mark == "@shencai_si" and not data.who:isNude() then
          local throw = table.random(player:getCardIds("he"), 1)
          room:throwCard(throw, "shencai", player, player)
        end
      end
      if not player:hasSkill("shencai") then
        room:handleAddLoseSkills(player,"shencai",nil,true)
        room:handleAddLoseSkills(player,"-shencai",nil,true)
    else
      end
    end
  elseif r <= 55 then
    local skills = {"ol_ex__chanyuan","ranshang","ty__zhixi","benghuai","chouhai","wumou","shiyong",}
    for _, s in ipairs(skills) do
      if player:hasSkill(s) then
        table.removeOne(skills,s)
      end
    end
    if skills and #skills > 0 then
      local s = table.random(skills,1)
      room:doBroadcastNotify("ShowToast", "超级盲盒：奖励一个秘密技能。")
      room:addPlayerMark(player,"manghe_lose-phase",1)
      room:handleAddLoseSkills(player,s,nil,true)
    else
      room:doBroadcastNotify("ShowToast", "超级盲盒也是空空如也")
      random2(room,player)
    end
  elseif r <= 60 then
    local m = room.settings.generalNum
    if #room.general_pile < m then
      local genss = room:getBanner("@&Allgenerals")
      if #genss > 0 then
        room:returnToGeneralPile(genss)
      end
    end
    local gg = room:getNGenerals(m)
    room:broadcastPlaySound("./audio/system/losemaxhp")
    room:doBroadcastNotify("ShowToast", "超级盲盒:选择一个武将作为你的副将。")
    local g = room:askForGeneral(player,gg,1,false)
    --判断是否为选项内武将
    if not table.contains(gg,g) then
      g = table.random(gg)
    end
    table.removeOne(gg,g)
    room:changeHero(player,g,false,true,true,false)
    room:returnToGeneralPile(gg)
    local Allgenerals = room:getBanner("@&Allgenerals")
    table.insertIfNeed(Allgenerals,player.deputyGeneral)
    room:setBanner("@&Allgenerals", Allgenerals)
    if player.deputyGeneral ~= "" and #Fk.generals[player.deputyGeneral].skills > 0 then
      for _, s in ipairs(Fk.generals[player.deputyGeneral].skills) do
        if s:isInstanceOf(TriggerSkill) and type(s.events) == "table" and table.contains(s.events,fk.GameStart) then
          s:trigger(fk.GameStart, player, player, nil)
        end
      end
    end
  elseif r <= 65 then
  --[[
    local ag = room:getBanner("@layers") or 0
    local m = math.random(3,9)
    if ag < 50 then
        m = math.min(m,49 - m)
    elseif ag < 100 then
        m = math.min(m,99 - m)
    end
    local n = 0
    for _, p in ipairs(room.players) do
      if p.role == "rebel" then
        n = n + 1
      end
    end
    ag = ag + m
    room:doBroadcastNotify("ShowToast", "超级盲盒：增加击杀进度"..m.."层！")
    for i = 1,m,1 do
    local Allgenerals = room:getBanner("@&Allgenerals")
    if #room.general_pile < n then
      local genss = room:getBanner("@&Allgenerals")
      room:returnToGeneralPile(genss)
    end
    local gb = room:getNGenerals(n)
    for _, g in ipairs(gb) do
      table.insertIfNeed(Allgenerals,g)
    end
    room:setBanner("@&Allgenerals", Allgenerals)
    canreward(room)
    end]]
    random2(room,player)
  elseif r <= 75 then
    local m = math.random(1,5)
    room:doBroadcastNotify("ShowToast", "超级盲盒：增加"..m.."体力上限并回复等量体力！")
    room:changeMaxHp(player,m)
    if player:isWounded() then
      room:recover({
        who = player,
        num = math.min(m,player.maxHp - player.hp),
        recoverBy = player,
        skillName = "超级盲盒"
        })
    end
  elseif r <= 80 then
    local skills = {"ol_ex__chanyuan","ranshang","ty__zhixi","benghuai","chouhai","wumou","shiyong",}
    local have = false
    for _, s in ipairs(skills) do
      if have then break end
      if player:hasSkill(s) then
        have = true
      end
    end
    if have then
      room:doBroadcastNotify("ShowToast", "超级盲盒为你清除了负面技。")
      for _, s in ipairs(skills) do
        if player:hasSkill(s) then
          room:handleAddLoseSkills(player,"-"..s,nil,true)
        end
      end
    else
      random2(room,player)
    end
  elseif r <= 85 and player:getMark("tshu_lightning-turn") == 0 then
    local m = math.random(9,18)
    local mm = m*3
    room:doBroadcastNotify("ShowToast", "超级盲盒:开始进行"..mm.."次不可更改的闪电判定。")
    local max = mm//10 + 1
    for i = 1,max, 1 do
      if player.dead then break end
      local da = 0
      local need = 0
      if mm > 10 then
        need = 10
        mm = mm - 10
      elseif mm > 0 then
        need = mm
        mm = 0 
      else
        break
      end
      local show = room:getNCards(need)
      room:moveCards({ ids = show, toArea = Card.Processing, moveReason = fk.ReasonJudge, skillName = "lightning_skill", proposer = player.id })
      for _, cid in ipairs(show) do
        local c = Fk:getCardById(cid)
        if c.number >= 2 and c.number <= 9 and c.suit == Card.Spade then
          room:setCardEmotion(cid, "judgegood")
          da = da + 1
        else
          room:setCardEmotion(cid, "judgebad")
        end
        room:delay(200)
      end
      room:moveCards({ ids = show, toArea = Card.DiscardPile, moveReason = fk.ReasonJudge })
      if da > 0 then
        for h = 1, da, 1 do
        room:delay(500)
          if player.dead then break end
          room:damage{
            to = player,
            damage = 3,
            damageType = fk.ThunderDamage,
            skillName = "lightning_skill",
          }
        end
      end
      if player.dead then break end
    end
    if not player.dead then
      local n = m//3
      room:doBroadcastNotify("ShowToast", "渡劫成功！奖励"..n.."次超级盲盒。")
      room:setPlayerMark(player,"tshu_lightning-turn",1)
      for i = 1, n, 1 do
        random2(room,player)
      end
    end
  elseif r <= 85 then
    random2(room,player)
  elseif r <= 86 then
    local over = false
        local all = player._splayer:getGameData():at(0)
        local win = player._splayer:getGameData():at(1)
        local lose = all - win
        if lose == 0 then
          over = true
        end
    if over then
    room:delay(300)
    local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
    table.insertIfNeed(jl,"tshujl__nianshou")
    --if nover then
      room:doBroadcastNotify("ShowToast", "恭喜抽中大奖！")
      room:doBroadcastNotify("ShowToast", "恭喜抽中大奖！")
      room:doBroadcastNotify("ShowToast", "恭喜抽中大奖！")
      room:delay(500)
    --end
    if not room.settings.enableDeputy then
      room:doBroadcastNotify("ShowToast", "★超级盲盒：已为"..Fk:translate(player.general).."【将灵池】永久解锁将灵——“年兽”！★")
    else
      room:doBroadcastNotify("ShowToast", "★【将灵池】已解锁将灵——“年兽”！")
    end
    for _, s in ipairs(Fk.generals["tshujl__nianshou"].skills) do
      room.players[1]:broadcastSkillInvoke(s.name)
      break
    end
    room:setBanner("@&tshu__jl",jl)
    room:delay(300)
    if not room.settings.enableDeputy then
      nianshou(room,player)
    end
    else
        random2(room,player)
    end
  else
    random2(room,player)
  end
end

--小盲盒
local function random(room, player,qd)
  ---摸牌，回血，弃牌，失去血量，放乐放兵，翻面，获得额外一个天书技能，获得一把铁匠武器，获得一个霹雳车大攻车，选择弃置1个天书技能，获得节应标记，跳过本回合选将,选择武将
  local r = math.random(1,16)
  if qd then
    for i = 1, 99, 1 do
      if r == 3 or r ==4 or r == 5 or r == 6 or r == 10 or r == 11 or r == 12   then
         r = math.random(1,16)
      else
        break
      end
    end
    room:doBroadcastNotify("ShowToast", "庆典日！！！")
  end
  if r == 1 then
    local cc = math.random(2,10)
    room:doBroadcastNotify("ShowToast", "盲盒奖励：摸"..cc.."张牌。")
    player:drawCards(cc,"盲盒")
  elseif r == 2 then
    if player:isWounded() then
      local cc = math.random(1,player.maxHp - player.hp)
      room:doBroadcastNotify("ShowToast", "盲盒奖励：回复"..cc.."点体力。")
      room:recover({
        who = player,
        num = cc,
        recoverBy = player,
        skillName = "盲盒"
        })
    else
      room:doBroadcastNotify("ShowToast", "似乎无事发生。")
      random(room,player)
    end
  elseif r == 3 then
    if player:isNude() then
      room:doBroadcastNotify("ShowToast", "似乎无事发生。")
      random(room,player)
    else
      local cc = math.random(1,10)
      room:doBroadcastNotify("ShowToast", "盲盒惩罚：弃置"..cc.."张牌。")
      room:askForDiscard(player,cc,cc,true,"盲盒",false)
    end
  elseif r == 4 then
    if not player:hasDelayedTrick("indulgence") then
      
      local cards = room:getNCards(1)
      if cards then
        room:doBroadcastNotify("ShowToast", "盲盒给你贴了张【乐不思蜀】。")
        local card = Fk:cloneCard("indulgence")
        card:addSubcards(cards)

        room:useCard{
          from = player.id,
          tos = {{player.id}},
          card = card,
          }
      else
          room:doBroadcastNotify("ShowToast", "似乎无事发生。")
          random(room,player)
      end
    else
      room:doBroadcastNotify("ShowToast", "盲盒里面空空如也。")
      random(room,player)
    end
  elseif r == 5 then
    if not player:hasDelayedTrick("supply_shortage") then
    local cards = room:getNCards(1)
    if cards then
      room:doBroadcastNotify("ShowToast", "盲盒给你贴了张【兵粮寸断】。")
      local card = Fk:cloneCard("supply_shortage")
      card:addSubcards(cards)

      room:useCard{
        from = player.id,
        tos = {{player.id}},
        card = card,
        }
    else
        room:doBroadcastNotify("ShowToast", "似乎无事发生。")
        random(room,player)
    end
    else
      room:doBroadcastNotify("ShowToast", "盲盒里面空空如也。")
      random(room,player)
    end
  elseif r == 6 then
    room:broadcastPlaySound("./packages/shzl/audio/skill/fangzhu2")
    room:doBroadcastNotify("ShowToast", "曹丕很喜欢你。")
    player:turnOver()
  elseif r == 7 then
    room:doBroadcastNotify("ShowToast", "盲盒奖励：获得一个额外的天书技能。")
    tianshu1(room,player,1,10)
  elseif r == 8 then
    local heart = {{"red_spear",Card.Heart,1}}
    local diamond = {{"quenched_blade",Card.Diamond,1}}
    local spade = {{"poisonous_dagger",Card.Spade,1}}
    local club = {{"water_sword",Card.Club,1}}
    local thunder = {{"thunder_blade",Card.Spade,1}}
    local dao = {heart,diamond,spade,club,thunder}
    local nm = math.random(1,5)
    local get = false
    local blade = table.find(U.prepareDeriveCards(room, dao[nm], "dao"..nm), function (id)
      local area = player.room:getCardArea(id)
        return area == Card.Void or area  == Card.DrawPile or  area == Card.DrawPile 
    end)
     if blade then
        room:moveCards({
          ids = {blade},
          fromArea = Card.Void,
          to = player.id,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player.id,
          skillName = "盲盒",
          })
        room:doBroadcastNotify("ShowToast", "盲盒奖励：来自铁匠的刀")
        if math.random(1,5) == 1 then
          room:doBroadcastNotify("ShowToast", "盲盒知道你刀拿不稳，给你的天书添加了【奇才】")
          local mark = player:getTableMark("@[tshu__tianshu]")
          table.insertIfNeed(mark,"joyex__qicai")
          room:setPlayerMark(player,"@[tshu__tianshu]",mark)
          room:handleAddLoseSkills(player,"joyex__qicai",nil,true)
        end
    else
        room:doBroadcastNotify("ShowToast", "盲盒里面空空如也。")
        random(room,player)
    end
  elseif r == 9 then
    local poyuan_catapult = {{"ty__catapult", Card.Diamond, 9}}
    local wanglu_engine = {{"siege_engine", Card.Spade, 9}}
    if math.random(1,2) == 1 then
      local engine = table.find(U.prepareDeriveCards(room, wanglu_engine, "wanglu_engine"), function (id)
        local area = player.room:getCardArea(id)
        return area == Card.Void or area  == Card.DrawPile or  area == Card.DrawPile
      end)
      if engine and U.canMoveCardIntoEquip(player, engine) then
        room:doBroadcastNotify("ShowToast", "大粪车，启动！")
        for i = 1, 3, 1 do
          room:setPlayerMark(player, "xianzhu"..tostring(i), 0)
        end
        U.moveCardIntoEquip (room, player, engine,"盲盒", true, player)
      else
        room:doBroadcastNotify("ShowToast", "盲盒里的东西似乎已经被取走了。")
        random(room,player)
      end
    else
      local catapult = table.find(U.prepareDeriveCards(player.room, poyuan_catapult, "poyuan_catapult"), function (id)
        local area = player.room:getCardArea(id)
        return area == Card.Void or area  == Card.DrawPile or  area == Card.DrawPile 
      end)
      if catapult and  U.canMoveCardIntoEquip(player, catapult) then
        room:doBroadcastNotify("ShowToast", "霹雳车，启动！")
        U.moveCardIntoEquip (room, player, catapult,"盲盒", true, player)
      else
        room:doBroadcastNotify("ShowToast", "盲盒里的东西似乎已经被取走了。")
        random(room,player)
      end
    end
  elseif r == 10 then
    room:doBroadcastNotify("ShowToast", "盲盒惩罚：移除一个天书技能。")
    remove(room,player,1)
  elseif r == 11 then
    room:doBroadcastNotify("ShowToast", "盲盒奖励你一个“节应”标记。")
    if not player:hasSkill("ty__jieying") then
      room:handleAddLoseSkills(player,"ty__jieying",nil,true)
      player.room:setPlayerMark(player, "@ty__jieying", {})
      room:handleAddLoseSkills(player,"-ty__jieying",nil,true)
    else
      player.room:setPlayerMark(player, "@ty__jieying", {})
    end
  elseif r == 12 then
    if room:getBanner("@layers") and room:getBanner("@layers")%5 == 0 then
      room:doBroadcastNotify("ShowToast", "本回合你不准选将！")
      room:setPlayerMark(player,"tshu__choose-turn",1)
    else
      room:doBroadcastNotify("ShowToast", "似乎无事发生。")
      random(room,player)
    end
  elseif r == 13 then
    room:doBroadcastNotify("ShowToast", "盲盒奖励：选择一次武将。")
    addGenerals(player)
  elseif r == 14 then
    --[[
    local ag = room:getBanner("@layers") or 0
    local m = math.random(3,10)
    if ag < 50 then
        m = math.min(m,49 - m)
    elseif ag < 100 then
        m = math.min(m,99 - m)
    end
    local n = 0
    for _, p in ipairs(room.players) do
      if p.role == "rebel" then
        n = n + 1
      end
    end
    ag = ag + m
    room:doBroadcastNotify("ShowToast", "盲盒：增加击杀进度"..m.."层。")
    for i = 1,m,1 do
    local Allgenerals = room:getBanner("@&Allgenerals")
    if #room.general_pile < n then
      local genss = room:getBanner("@&Allgenerals")
      room:returnToGeneralPile(genss)
    end
    local gb = room:getNGenerals(n)
    for _, g in ipairs(gb) do
      table.insertIfNeed(Allgenerals,g)
    end
    room:setBanner("@&Allgenerals", Allgenerals)
    canreward(room)
    end
    ]]
    random(room,player)
  elseif r == 15 then
    room:doBroadcastNotify("ShowToast", "获得一次超级盲盒机会！")
    random2(room,player)
  elseif r == 16 then
    local n = math.random(1,10)
          room:doBroadcastNotify("ShowToast", "盲盒奖励：获得"..n.."张“天书残页”")
          room:delay(300)
          room:setBanner("@tshu__coin", (room:getBanner("@tshu__coin") or 0) + n)
          room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__canye")
          room:delay(300)
  end
end
----判断是否有奖励
local function reward(player)
  local room = player.room
  local ag = room:getBanner("@layers") or 0
  local mark = player:getTableMark("@[tshu__tianshu]")
  local n = mark and #mark or 0
  ----每5层触发一次
  if n < 5 or ag % 5 == 0 then

    ---每10个技能有一个觉醒/限定技
    if n and n > 0 and ((n+1)%10) == 0 and n < 10 then
      tianshu2(room,player,1,10)
    elseif not n or n < 10 then
      tianshu1(room,player,1,10)
    end

    ----每20次层一次大奖励
      if ag%20 == 0 then
        local choices1 = {"tshu_draw2"}
        if  player:isWounded() then
          table.insertIfNeed(choices1,"tshu_recover2")
        end
        table.insertIfNeed(choices1,"放弃奖励")
        local choice1 = room:askForChoice(player,choices1,"天书奖励",nil,true,{"tshu_draw2","tshu_recover2","放弃奖励"})
        if choice1 == "tshu_draw2" then
          local f = player:getMaxCards() - player:getHandcardNum()
          if not player.dead  then
            player:drawCards(math.max(f,2),"天书奖励")
          end
        elseif choice1 == "tshu_recover2" then
          if not player.dead and player:isWounded() then
            room:recover({
              who = player,
              num = player.maxHp - player.hp,
              recoverBy = player,
              skillName = player.name
              })
          end
        end
        if not player.dead and n and n >= 4 then
          local choices2 = {"tshu_skill2","tshu_random2","放弃奖励"}
          local choice2 = room:askForChoice(player,choices2,"天书奖励",nil,true)
          if choice2 == "tshu_skill2" then
              remove(room,player,1)
              tianshu2(room,player,1,5)
          elseif choice2 == "tshu_random2" then
            random2(room,player)
          end
        end
      else
        local choices1 = {"tshu_draw1"}
        if  player:isWounded() then
          table.insertIfNeed(choices1,"tshu_recover1")
        end
        table.insertIfNeed(choices1,"放弃奖励")
        local choice1 = room:askForChoice(player,choices1,"天书奖励",nil,true,{"tshu_draw1","tshu_recover1","放弃奖励"})
        if choice1 == "tshu_draw1" then
          if not player.dead  then
            player:drawCards(2,"天书奖励")
          end
        elseif choice1 == "tshu_recover1" then
          if not player.dead and player:isWounded() then
            room:recover({
              who = player,
              num = 1,
              recoverBy = player,
              skillName = "天书奖励"
              })
          end
        end
        if not player.dead and n and n >= 4 then
          local choices2 = {"tshu_skill1","tshu_random1","放弃奖励"}
          local choice2 = room:askForChoice(player,choices2,"天书奖励",nil,true)
          if choice2 == "tshu_skill1" then
              remove(room,player,1)
              tianshu1(room,player,1,5)
          elseif choice2 == "tshu_random1" then
            random(room,player)
          end
        end
      end
      
    end
    --换将刷新
      if ag%5 == 0 then
        room:setPlayerMark(player,"changeago",0)
        room:setPlayerMark(player,"changejlago",0)
      end
      ----武将
      if ag % 5 == 0  and player:getMark("tshu__choose-turn") == 0 then
        addGenerals(player)
        --changeGeneral(player)
      end
      
end

--偶像
local function getox(room,oxn)
  local g = oxn
  for _, p in ipairs(room.players) do
    if p.role == "renegade" and p.dead then
      p:bury()
      room:resumePlayerArea(p, p.sealedSlots)
      if g ~= p.general then
      local to_rm = table.filter(p.player_skills, function(s)
        return not s.attached_equip and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
       end)
      room:handleAddLoseSkills(p, table.concat(
         table.map(to_rm, function(s) return "-" .. s.name end), "|"), nil, true)
      end
      room:changeHero(p, g, true, false, true)
      if room:getBanner("@[:]tshu__gongskill") and  room:getBanner("@[:]tshu__gongskill") ~= 0 then
        room:handleAddLoseSkills(p,room:getBanner("@[:]tshu__gongskill"),nil,true,true)
      end

        -- trigger leave

      room:revivePlayer(p, false)
      room:setPlayerProperty(p, "kingdom", "god")
      --room:setPlayerProperty(p, "hp", Fk.generals[g].hp)
      room:changeMaxHp(p,(room:getBanner("@layers") or 0)//20 )
      p.room:recover({
      who = p,
      num = (room:getBanner("@layers") or 0)//20,
      recoverBy = p,
      skillName = "奖励"
      })
      break
    end
  end
end
--生成偶像
local function addox(room)
  local need = {"slash","analeptic","peach","indulgence","jink"}
  local tos = {}
  for _, p in ipairs(room.alive_players) do
    if (p.role == "lord" or p.role == "loyalist") and not p:isKongcheng() then
      for _, cid in ipairs(p:getCardIds(Player.Hand)) do
        local c = Fk:getCardById(cid)
        if table.contains(need,c.trueName) then
          table.insertIfNeed(tos,p)
        end
      end
    end
  end
  local extraData = {
    num = 1,
    min_num = 1,
    include_equip = true,
    pattern = "jink,slash,peach,indulgence,analeptic",
    reason = "召唤偶像",
  }
  if #tos > 0 then
  local cards = {}
  for _, p in ipairs(tos) do
    p.request_data = json.encode({ "choose_cards_skill", "#tshu__addox", true, extraData })
  end
  room:notifyMoveFocus(room.alive_players,"召唤偶像")
  room:doBroadcastRequest("AskForUseActiveSkill", tos)
  for _, p in ipairs(tos) do
    local id
    if p.reply_ready then
      local replyCard = json.decode(p.client_reply).card
      id = json.decode(replyCard).subcards[1]
    else
      for _, cid in ipairs(p:getCardIds(Player.Hand)) do
        local c = Fk:getCardById(cid)
        if table.contains(need,c.trueName) then
          id = cid
        end
      end
    end
    p:showCards({Fk:getCardById(id)})
    table.insertIfNeed(cards,id)
  end
    if #cards > 0 then
      local name = {}
      for _, cid in ipairs(cards) do
        local c = Fk:getCardById(cid)
        table.insert(name,c.name)
      end
      table.insert(name,table.random(need))
      local gox = table.random(name)
      local ox = {"tshuox__xiaosha","tshuox__xiaojiu","tshuox__xiaotao","tshuox__xiaole","tshuox__xiaoshan"}
      local oxn
      for i = 1, 5, 1 do
        if need[i] == gox then
          oxn = ox[i]
          break
        end
      end
      room:doBroadcastNotify("ShowToast", "根据玩家展示手牌与一个随机牌名召唤虚拟偶像")
      if not oxn then
        oxn = ox[math.random(1,5)]
        if oxn then
            getox(room,oxn)
            room:doBroadcastNotify("ShowToast", "已召唤一个随机偶像")
        else
            room:doBroadcastNotify("ShowToast", "召唤偶像失败，请联系北冰洋T汇报相关bug！")
        end
      else
        getox(room,oxn)
      end
    end
  end
end


--刷怪
local function boss(player)
  local deputyHp = player:getMark("@deputyHp")
  local room = player.room
  if deputyHp < 1 then
    room:changeHero(player, "", false, true, true)
  end
  local ag = room:getBanner("@layers") or 0
  local spgod = {"tshugod__jiaxu1","tshugod__jiaxu2"}
  local tgodboss = {"tshugod__kuafu","tshugod__shaohao","tshugod__xuannv","tshugod__hanba","tshugod__caoe","tshugod__taoshen","tshugod__hebo","tshugod__yanluowang","tshugod__yuershen"}
  local tnx = {"tshunx__nwei","tshunx__nqun","tshunx__nshu","tshunx__nwu","tshunx__xwu","tshunx__xwei","tshunx__xqun","tshunx__xshu","tshusx__shu","tshusx__niu","tshusx__hu","tshusx__tu","tshusx__long","tshusx__she","tshusx__ma","tshusx__yang","tshusx__hou","tshusx__ji","tshusx__gou","tshusx__zhu"}
  local no = {"tshunx__pucong"}
  local ss = {"tshuss__qinglong","tshuss__zhuque","tshuss__baihu","tshuss__xuanwu"}
  local xx = {"tshuxx__jiaomujiao","tshuxx__kangjinlong","tshuxx__yihuoshe","tshuxx__xingrima","tshuxx__kuimulang","tshuxx__canshuiyuan","tshuxx__doumuxie","tshuxx__weiyueyan"}
  local god = {}
  local ggod = {}
  local godboss = {}
  local nx = {}
  local jiaxu = false
  if ag == 99 or (((ag+1)%100 == 0) and math.random(1,5) == 1 ) then
    jiaxu = true
  end
  if (ag == 3 or ag == 4 or (((ag + 1)%10 == 0 ))) then
    local tgod = {"godjiaxu","godxuchu","godcaopi","goddengai","godzhouyu","joy__godzuoci","joy__goddianwei", "godliubei","goddiaochan","godzhenji","joy__goddaxiaoqiao","godhuatuo","godzhaoyun", "godganning","godguanyu","godcaocao", "godtaishici","godlvbu","godlvmeng","godzhangliao","godsunquan","godmachao","godzhangjiao","godjiangwei","godxunyu","godsunce","godguojia","godluxun","godsimayi","godzhugeliang"}
    god = table.simpleClone(tgod)
    for _, g in ipairs(tgod) do
      for _, n in ipairs(Fk:getSameGenerals(g)) do
        table.insertIfNeed(god,n)
      end
    end
    ggod = table.simpleClone(god)
    for _, General in ipairs(god) do
      if table.contains(room:getBanner("@&Allgenerals"),General) then
        table.removeOne(ggod,General)
      end
    end
    if #ggod <= 0 then
      ggod = table.simpleClone(god)
    end
  end
  local gb = room:getBanner("@&godboss")
  if (ag == 4 or ag == 39 or ag == 79 or ((ag+1)%100 == 0) ) then
    godboss = table.simpleClone(tgodboss)
    for _, General in ipairs(tgodboss) do
      if table.contains(gb,General) then
        table.removeOne(godboss,General)
      end
    end
    if #godboss <= 0 then
      room:setBanner("@&godboss",{})
      godboss = table.simpleClone(tgodboss)
    end
  end
  if ag == 2 or  (ag + 1)%15 == 0 then
    nx = table.simpleClone(tnx)
    for _, General in ipairs(tnx) do
      if table.contains(gb,General) then
        table.removeOne(nx,General)
      end
    end
  end
  local r = 0
  local ar = 0
  for _, p in ipairs(room.players) do
    if p.role == "rebel" then
      ar = ar + 1
    end
  end
  for _, p in ipairs(room.alive_players) do
    if p.role == "rebel" then
      r = r + 1
    end
  end
  local g
  if (ag == 4 or (ag == 4 or ag == 39 or ag == 79 or ag == 99 or ((ag+1)%100 == 0)) ) and #godboss > 0 and (r >= (ar - 2)//2) and (r < (((ar - 2)//2) + 2 ))  then
    g = table.random(godboss,1)[1]
    if jiaxu then
      local jia = true
      for _, p in ipairs(room.players) do
        if p.general == "tshugod__jiaxu1" or p.general == "tshugod__jiaxu2" then
          jia = false
        end
      end
      if jia then
        g = "tshugod__jiaxu2"
      end
    end
  elseif ag == 2 or  (ag + 1)%15 == 0 then
    if #nx > 0 and (r >= (ar - 3)//2) and (r < (((ar - 3)//2) + 3 )) then
      g = table.random(nx,1)[1]
    else
      g = "tshunx__pucong"
    end
  elseif (ag == 3 or ag == 4 or (((ag + 1)%10 == 0 ))) and #ggod > 0 then
    g = table.random(ggod,1)[1]
  elseif (room:getBanner("tshuss") and room:getBanner("tshuss") or 0) == 1 and (ag+1)%5 ~= 0 and (r >= (ar - 3)//2) and (r < (((ar - 3)//2) + 3 )) then
    if ((ag+1)%10)%4 == 0 then
      if (r == ((ar - 3)//2) + 1) then
        g = "tshuss__xuanwu"
      elseif (r == ((ar - 3)//2) ) then
        g = "tshuxx__weiyueyan"
      elseif (r == ((ar - 3)//2) + 2 ) then
        g = "tshuxx__doumuxie"
      end
    elseif ((ag+1)%10)%3 == 0 then
      if (r == ((ar - 3)//2) + 1) then
        g = "tshuss__baihu"
      elseif (r == ((ar - 3)//2) ) then
        g = "tshuxx__kuimulang"
      elseif (r == ((ar - 3)//2) + 2 ) then
        g = "tshuxx__canshuiyuan"
      end
    elseif ((ag+1)%10)%2 == 0 then
      if (r == ((ar - 3)//2) + 1) then
        g = "tshuss__zhuque"
      elseif (r == ((ar - 3)//2) ) then
        g = "tshuxx__yihuoshe"
      elseif (r == ((ar - 3)//2) + 2 ) then
        g = "tshuxx__xingrima"
      end
    elseif ((ag+1)%10)%1 == 0 then
      if (r == ((ar - 3)//2) + 1) then
        g = "tshuss__qinglong"
      elseif (r == ((ar - 3)//2) ) then
        g = "tshuxx__jiaomujiao"
      elseif (r == ((ar - 3)//2) + 2 ) then
        g = "tshuxx__kangjinlong"
      end
    end
  else
    if #room.general_pile < 1 then
      local genss = room:getBanner("@&Allgenerals")
      if #genss > 0 then
        room:returnToGeneralPile(genss)
      end
    end
    g = room:getNGenerals(1)[1]
  end
  local to_rm = table.filter(player.player_skills, function(s)
    return not s.attached_equip and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
   end)
  room:handleAddLoseSkills(player, table.concat(
     table.map(to_rm, function(s) return "-" .. s.name end), "|"), nil, true)
  if player.deputyGeneral ~= "" then
   for _,s in ipairs(Fk.generals[player.deputyGeneral].skills) do
     room:handleAddLoseSkills(player,s.name,nil,true)
   end
   for _,s in ipairs(Fk.generals[player.deputyGeneral].other_skills) do
     room:handleAddLoseSkills(player,s,nil,true)
   end
  end
  room:resumePlayerArea(player, player.sealedSlots)
room:setPlayerMark(player,"tshu__fpj-phase",1)
  room:changeHero(player, g, false, false, true)

        -- trigger leave

  room:revivePlayer(player, false)
  room:setPlayerRest(player,0)
  room:setPlayerProperty(player, "kingdom", Fk.generals[g].kingdom)
  room:setPlayerProperty(player, "hp", Fk.generals[g].hp)
  room:setPlayerMark(player,"@deputyHp",deputyHp)
  if table.contains(godboss,g) or table.contains(nx,g) or table.contains(spgod,g)  then
    local Allgenerals = room:getBanner("@&godboss")
    table.insertIfNeed(Allgenerals,g)
    room:setBanner("@&godboss", Allgenerals)
  elseif table.contains(no,g) or table.contains(ss,g) or table.contains(xx,g)then

  else
    local Allgenerals = room:getBanner("@&Allgenerals")
    table.insertIfNeed(Allgenerals,g)
    room:setBanner("@&Allgenerals", Allgenerals)
  end
  
  if room:getBanner("tshu-hp") and room:getBanner("tshu-hp") > 0 then
    room:changeMaxHp(player,room:getBanner("tshu-hp") )
    room:setPlayerProperty(player, "hp", Fk.generals[g].hp + room:getBanner("tshu-hp"))
  end
  
  --庆典
  if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
    local qd = Fk.skills["tshu__qdian2"]
    room:useSkill(player,qd, function()
      return qd:use(fk.GameStart, player, player)
    end)
  end
   --boss技能
  local kill = room:getBanner("tshu-damage") or 0
  if kill and kill > 0 then
    tianshu1(room,player,kill,kill)
  end
  
  if (ag+1) == 50 then
    local jl = false
    for _, p in ipairs(room.alive_players) do
      if p.role == "rebel" and p:getMark("tshujl__guansuo") > 0 then
        jl = true
      end
      if jl then break end
    end
    if not jl and table.contains(godboss,g) then
      local mark = type(player:getMark("@&tshu__jlmark")) == "table" and player:getMark("@&tshu__jlmark") or {}
      table.insertIfNeed(mark,"tshujl__guansuo")
      room:setPlayerMark(player,"@&tshu__jlmark",mark)
      room:setPlayerMark(player,"tshujl__guansuo",1)
    end
  elseif (ag + 1) == 100 then
    local jl = false
    for _, p in ipairs(room.alive_players) do
      if p.role == "rebel" and p:getMark("tshujl__caochun") > 0 then
        jl = true
      end
    end
    if not jl and table.contains(godboss,g) then
      local mark = type(player:getMark("@&tshu__jlmark")) == "table" and player:getMark("@&tshu__jlmark") or {}
      table.insertIfNeed(mark,"tshujl__caochun")
      room:setPlayerMark(player,"@&tshu__jlmark",mark)
      room:setPlayerMark(player,"tshujl__caochun",1)
    end
  elseif (ag + 1) == 200 then
    local jl = false
    for _, p in ipairs(room.alive_players) do
      if p.role == "rebel" and p:getMark("tshujl__nianzhugeliang") > 0 then
        jl = true
      end
    end
    if not jl and table.contains(godboss,g) then
      local mark = type(player:getMark("@&tshu__jlmark")) == "table" and player:getMark("@&tshu__jlmark") or {}
      table.insertIfNeed(mark,"tshujl__nianzhugeliang")
      room:setPlayerMark(player,"@&tshu__jlmark",mark)
      room:setPlayerMark(player,"tshujl__nianzhugeliang",1)
    end
  elseif (ag + 1) == 300 or (ag + 1) == 400 or (ag + 1) == 500 then
    local jl = false
    for _, p in ipairs(room.alive_players) do
      if p.role == "rebel" and p:getMark("tshujl__nianlvbu") > 0 then
        jl = true
      end
    end
    if not jl and table.contains(godboss,g) then
      local mark = type(player:getMark("@&tshu__jlmark")) == "table" and player:getMark("@&tshu__jlmark") or {}
      table.insertIfNeed(mark,"tshujl__nianlvbu")
      room:setPlayerMark(player,"@&tshu__jlmark",mark)
      room:setPlayerMark(player,"tshujl__nianlvbu",1)
    else
      local jl2 = false
      for _, p in ipairs(room.alive_players) do
        if p.role == "rebel" and p:getMark("tshujl__miaolvlingqi") > 0 then
          jl2 = true
        end
      end
      if not jl2 and table.contains(godboss,g) then
        local mark = type(player:getMark("@&tshu__jlmark")) == "table" and player:getMark("@&tshu__jlmark") or {}
        table.insertIfNeed(mark,"tshujl__miaolvlingqi")
        room:setPlayerMark(player,"@&tshu__jlmark",mark)
        room:setPlayerMark(player,"tshujl__miaolvlingqi",1)
      end
    end
  end
  local draw = room:getBanner("tshu-cover") or 0
  if table.contains(godboss,g)  or table.contains(nx,g) or table.contains(no,g) or  table.contains(spgod,g) then
    --drawInit(room, player, math.max(5,player.hp + draw))
    player:drawCards(math.min(100,math.max(5,player.hp + draw)))
  else
    --drawInit(room, player, 5 + draw)
    player:drawCards(math.min(100,5+draw))
  end
  room:setPlayerMark(player,"tshu__fpj-phase",0)
end
  

--游戏胜利
local function tshu__gameOver(room)
  local self = room
  local winner = "lord"
  if not self.game_started then return end

  

  local ag = room:getBanner("@layers") or 0
  local notover = false
  local winners = {}
  local rank = 0
    for _, p in ipairs(self.players) do
      local id = p.id
      local general = p.general
      local mode = self.settings.gameMode

      if p.id > 0 then
        local win = p._splayer:getGameData():at(1)
        if p.role == "lord" or p.role == "loyalist" then
          table.insertIfNeed(winners,p)
          if ag == 5 then
            rank = 5
            if  win < 1  then
              self.room:updateWinRate(id, general, mode, 1, p.dead)
            elseif win >= 1 then
              notover = true
            end
          elseif ag == 50 then
            rank = 10
            if  win < 2  then
              self.room:updateWinRate(id, general, mode, 1, p.dead)
            elseif win >= 2 then
              notover = true
            end
          elseif ag == 100 then
            rank = 11
            if  win < 3  then
              self.room:updateWinRate(id, general, mode, 1, p.dead)
            elseif win >= 3 then
              notover = true
            end
          end
        end
      end
  end
--[[
  if notover then return end
  self:doBroadcastNotify("GameOver", winner)
  if table.contains(
    { "running", "normal" },
    coroutine.status(self.main_co)
  ) then
    self.logic:trigger(fk.GameFinished, nil, winner)
  end

  self.game_started = false
  self.game_finished = true


  if #winners > 0  then
    local mvp = table.random(winners)
		mvp:broadcastSkillInvoke("mobile_effect", 10)

    room:doSuperLightBox("packages/mobile_effect/qml/MobileMvp.qml", {
      general = mvp.general,
      screenName = mvp._splayer:getScreenName(),
      rank = rank,
      })
    room:delay(1100)
    local skill = Fk.skills[mvp.general .. "_win_audio"]
    if not skill then skill = table.random(Fk.generals[mvp.general].skills) end
    if skill then mvp:broadcastSkillInvoke(skill.name) end
    room:delay(2900)
  end
  
  self.room:gameOver()

  if table.contains(
    { "running", "normal" },
    coroutine.status(self.main_co)
  ) then
    coroutine.yield("__handleRequest", "over")
  else
    coroutine.close(self.main_co)
    self.main_co = nil
  --end

]]
  
end


--判断奖励
canreward = function (room)
  if room.tag["tshu_up"] and room.tag["tshu_up"] == 1 then
    room:doBroadcastNotify("ShowToast", "存在未结算完毕的晋层")
    return
  end
  room:setTag("SkipGameRule", true)
  room:setTag("RoundCount",1)
  room:setBanner("@layers", (room:getBanner("@layers") or 0) + 1)
  local ag = room:getBanner("@layers") or 0
  if ag >= 10 and ag%10 == 0 then
    local n = 5*(ag//10 + 1)
    if ag == 40 or ag == 80 or ag == 100 then
      n = n*2
    end
    n = math.min(n,60)
    if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
      n = n*2
      room:doBroadcastNotify("ShowToast", "庆典日！！！")
    end
    room:doBroadcastNotify("ShowToast", "通关奖励"..n.."张“天书残页”")
    room:setBanner("@tshu__coin", (room:getBanner("@tshu__coin") or 0) + n)
    room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__canye")
    for _, p in ipairs(room.players) do
      if (p.role == "lord" or p.role == "loyalist") and not p:hasSkill("tshu__store&") then
        room:handleAddLoseSkills(p,"tshu__store&",nil,true)
      end
    end
    room:delay(500)
  end
  if ag == 5 and not (room:getBanner("jump") and room:getBanner("jump") == 1 ) then
    local over,nover = false,false
    for _, p in ipairs(room.players) do
      if p.role == "lord" or p.role == "loyalist" then
        local win = p._splayer:getGameData():at(1)
        if win < 1 then
          over = true
        elseif win >= 1 then
          nover = true
        end
      end
    end
    if over then
      local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
      table.insertIfNeed(jl,"tshujl__caoying")
      --if nover and not room.settings.enableDeputy then
        room:doBroadcastNotify("ShowToast", "恭喜通关一周目。")
      --end
      if not room.settings.enableDeputy then
        room:doBroadcastNotify("ShowToast", "★已为所有玩家【将灵池】永久解锁将灵——“曹婴”！★")
      else
        room:doBroadcastNotify("ShowToast", "★【将灵池】已解锁将灵——“曹婴”！★")
      end
      for _, s in ipairs(Fk.generals["tshujl__caoying"].skills) do
        room.players[1]:broadcastSkillInvoke(s.name)
        break
      end
      room:setBanner("@&tshu__jl",jl)
      room:delay(300)
      if not room.settings.enableDeputy then
        tshu__gameOver(room)
      end
    else
      room:doBroadcastNotify("ShowToast", "★下个将灵————通关50层！")
    end
  end
  if ag >= 15 and not room:getBanner("@[:]tshu__gongskill") then
    local gjr
    for _, p in ipairs(room.alive_players) do
      if p.role == "lord" or p.role == "loyalist"  then
        gjr = p
        break
      end
    end
    local function filterfuc(skill)
      local str = Fk:translate(":"..skill.name)
      return not skill.lordSkill  and #skill.attachedKingdom == 0 and skill.frequency < Skill.Limited
      and not (string.find(str, "阵营") or string.find(str, "被动") or string.find(str, "超元气必杀") or 
      string.find(str, "元气") )
    end
    local gskills=T.getskillfrompool3(gjr,room,filterfuc,30,30,1)
    if gskills then
      for _, p in ipairs(room.alive_players) do
        if p.role == "renegade"  then
          room:handleAddLoseSkills(p,gskills[1],nil,true,true)
        end
      end
      room:setBanner("@[:]tshu__gongskill",gskills[1])
    end
  end
  if ag == 50 and not (room:getBanner("jump") and room:getBanner("jump") == 1 ) then
    local over,nover = false,false
    for _, p in ipairs(room.players) do
      if p.role == "lord" or p.role == "loyalist" then
        local win = p._splayer:getGameData():at(1)
        if win < 2 then
          over = true
        elseif win >= 2 then
          nover = true
        end
      end
    end
    if over then
    room:delay(300)
    local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
    table.insertIfNeed(jl,"tshujl__guansuo")
    table.insertIfNeed(jl,"tshujl__zhouyi")
    --if nover then
      room:doBroadcastNotify("ShowToast", "恭喜通关二周目！")
    --end
    if not room.settings.enableDeputy then
      room:doBroadcastNotify("ShowToast", "★已为所有玩家【将灵池】永久解锁将灵——“关索”&“周夷”！★")
    else
      room:doBroadcastNotify("ShowToast", "★【将灵池】已解锁将灵——“关索”&“周夷”！")
    end
    for _, s in ipairs(Fk.generals["tshujl__guansuo"].skills) do
      room.players[1]:broadcastSkillInvoke(s.name)
      break
    end
    for _, s in ipairs(Fk.generals["tshujl__zhouyi"].skills) do
      room.players[1]:broadcastSkillInvoke(s.name)
      break
    end
    room:setBanner("@&tshu__jl",jl)
    room:delay(300)
    if not room.settings.enableDeputy then
      tshu__gameOver(room)
    end
    else
    room:doBroadcastNotify("ShowToast", "★下个将灵————通关第百层！")
    end
  end
  if ag == 100 then
    room:doBroadcastNotify("ShowToast", "恭喜百战天书胜利！！！")
    room:doBroadcastNotify("ShowToast", "恭喜百战天书胜利！！！")
    room:doBroadcastNotify("ShowToast", "恭喜百战天书胜利！！！")
    room:delay(300)
    local over,nover = false,false
    for _, p in ipairs(room.players) do
      if p.role == "lord" or p.role == "loyalist" then
        local win = p._splayer:getGameData():at(1)
        if win < 3 then
          over = true
        elseif win >= 3 then
          nover = true
        end
      end
    end
    if over and not (room:getBanner("jump") and room:getBanner("jump") == 1 ) then
    local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
    table.insertIfNeed(jl,"tshujl__caochun")
    --if nover and not room.settings.enableDeputy then
    room:doBroadcastNotify("ShowToast", "恭喜通关三周目！")
    --end
    if not room.settings.enableDeputy then
      room:doBroadcastNotify("ShowToast", "★已为所有玩家【将灵池】永久解锁将灵——“曹纯”！★")
    else
      room:doBroadcastNotify("ShowToast", "★【将灵池】已解锁将灵——“曹纯”！")
    end
    for _, s in ipairs(Fk.generals["tshujl__caochun"].skills) do
      room.players[1]:broadcastSkillInvoke(s.name)
      break
    end
    room:setBanner("@&tshu__jl",jl)
    room:delay(300)
    if not room.settings.enableDeputy then
      tshu__gameOver(room)
    end
    else
    room:doBroadcastNotify("ShowToast", "接下来等待你们的便是无尽的挑战。")
    end
  elseif ag == 200 and not (room:getBanner("jump") and room:getBanner("jump") == 1 ) then
    room:doBroadcastNotify("ShowToast", "居然通关了两百层！！！")
    room:doBroadcastNotify("ShowToast", "居然通关了两百层！！！")
    room:doBroadcastNotify("ShowToast", "居然通关了两百层！！！")
    if not room.settings.enableDeputy and room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian"  then
      
      for _, p in ipairs(room.players) do
        if p.role == "lord" or p.role == "loyalist" then
          local win = p._splayer:getGameData():at(1)
          if win == 3 then
            if room:getBanner("tshu__sajia") and room:getBanner("tshu__sajia") > 0  then
              room:doBroadcastNotify("ShowToast", "检测到房间使用过“撒迦”将灵，无法成功解锁“念·诸葛亮”")
              room:delay(500)
            elseif p:getMark("tshujl__nianzhugeliang") > 0 then
              nianzhuge(room,p)
              room:doBroadcastNotify("ShowToast", "★庆典日！已为 "..Fk:translate(p.general).." 【将灵池】永久解锁将灵——“念·诸葛亮”！★")
              room:delay(500)
            else
              room:doBroadcastNotify("ShowToast", ""..Fk:translate(p.general).."没有携带“念·诸葛亮”,跳过解锁")
              room:delay(500)
            end
          end
        end
      end
    end
  elseif ag == 300 then
    room:doBroadcastNotify("ShowToast", "击杀三百层？你是神仙吗！！！")
    room:doBroadcastNotify("ShowToast", "击杀三百层？你是神仙吗！！！")
    room:doBroadcastNotify("ShowToast", "击杀三百层？你是神仙吗！！！")
  elseif ag == 500 then
    room:doBroadcastNotify("ShowToast", "五百层！已经超过我的理解程度了！！！")
    room:doBroadcastNotify("ShowToast", "五百层！已经超过我的理解程度了！！！")
    room:doBroadcastNotify("ShowToast", "五百层！已经超过我的理解程度了！！！")
    room:doBroadcastNotify("ShowToast", "五百层！已经超过我的理解程度了！！！")
    room:doBroadcastNotify("ShowToast", "五百层！已经超过我的理解程度了！！！")
  end

  --关卡加成
  if ag >= 10 and (ag%10 == 1 or ag%10 == 3 or ag%10 == 6 or ag%10 == 8) then
    room:setBanner("tshu-hp", (room:getBanner("tshu-hp") or 0) + 1)
  elseif ag >= 10 and ag%10 == 0 then
    room:setBanner("tshu-damage", (room:getBanner("tshu-damage") or 0) + 1)
  elseif ag >= 10 and (ag%10 == 2 or ag%10 == 7) then
    room:setBanner("tshu-start", (room:getBanner("tshu-start") or 0) + 1)
  elseif  ag >= 10 and (ag%10 == 4 or ag%10 == 9) then
    room:setBanner("tshu-finish", (room:getBanner("tshu-finish") or 0) + 1)
  elseif  ag >= 10 and ag%10 == 5  then
    room:setBanner("tshu-cover", (room:getBanner("tshu-cover") or 0) + 1)
  end
  if #room.general_pile < 20 then
    local genss = room:getBanner("@&Allgenerals")
    if #genss > 0 then
      room:returnToGeneralPile(genss)
      room:doBroadcastNotify("ShowToast", "将池不足，将重洗将池")
    end
  end
  local current = room.logic:getCurrentEvent()
  local last_event = nil
  if room.current.dead then
    last_event = current:findParent(GameEvent.Turn, true)
  end
  if last_event == nil then
    last_event = current
    if last_event.parent then
      repeat
        if table.contains({GameEvent.Round, GameEvent.Turn, GameEvent.Phase}, last_event.parent.event) then break end
        last_event = last_event.parent
      until (not last_event.parent)
    end
  end
  local lord
  for _, p in ipairs(room.players) do
    if  p.role == "lord" then
      lord = p
    end
  end
  last_event:addExitFunc(function()
    
    local ag2 = room:getBanner("@layers") or 0
    if ag2 >= 5 then
      local sajia = false
      for _, p in ipairs(room.players) do
        if (p.role == "lord" or p.role == "loyalist") and  p:getMark("tshujl__sajia") > 0 then
          sajia = true
          p:broadcastSkillInvoke("tshujl__chuangshi")
          room:doBroadcastNotify("ShowToast", "撒迦 的力量 消耗了“天书残页”来加速天书进度")
          room:delay(500)

          --
          local n = 5*(ag//10 + 1)
          if ag == 40 or ag == 80 or ag == 100 then
            n = n*2
          end
          n = math.min(n,60)
          if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
            n = n*2
          end
          room:setBanner("@tshu__coin", math.max(0,(room:getBanner("@tshu__coin") or 0) - (n//4)))
          --
          break
        end
      end
      if sajia then
        for i = 1, 5, 1 do
          if (ag2 + 1)%5 == 0 then
            break
          end
          ag2 = ag2 + 1
          if ag2 >= 10 and (ag2%10 == 1 or ag2%10 == 3 or ag2%10 == 6 or ag2%10 == 8) then
            room:setBanner("tshu-hp", (room:getBanner("tshu-hp") or 0) + 1)
          elseif ag2 >= 10 and ag2%10 == 0 then
            room:setBanner("tshu-damage", (room:getBanner("tshu-damage") or 0) + 1)
          elseif ag2 >= 10 and (ag2%10 == 2 or ag2%10 == 7) then
            room:setBanner("tshu-start", (room:getBanner("tshu-start") or 0) + 1)
          elseif  ag2 >= 10 and (ag2%10 == 4 or ag2%10 == 9) then
            room:setBanner("tshu-finish", (room:getBanner("tshu-finish") or 0) + 1)
          elseif  ag2 >= 10 and ag2%10 == 5  then
            room:setBanner("tshu-cover", (room:getBanner("tshu-cover") or 0) + 1)
          end
        end
      end
      room:setBanner("@layers",ag2)
    end
    if #room.general_pile < 1 then
      local genss = room:getBanner("@&Allgenerals")
      if #genss > 0 then
        room:returnToGeneralPile(genss)
      end
    end
    room.tag["tshu_up"] = 1
    for _, p in ipairs(room.players) do
      if p.dead and p.role == "rebel" then
        boss(p)
      end
    end
    room.tag["tshu_up"] = nil
    for _, p in ipairs(room.players) do
      if  p.role == "rebel" then
        restart(p)
      end
    end
    if  not room.settings.enableDeputy then
        --room.current = room.current.next
        room.logic:breakTurn()
    end
  end)
  ----玩家奖励技能
  for _, p in ipairs(room.alive_players) do
    if p.role == "lord" or p.role == "loyalist" then
      reward(p)
    end
  end
  
   local renegade
  local yes = true
  for _, p in ipairs(room.players) do
    if  p.role == "renegade" then
      yes = false
      renegade = p
    end
  end

  if ag >= 5 and ag%5 == 0 and yes  then
      local rebel = false
      for _, p in ipairs(room.players) do
        if rebel then break end
        if p.role == "rebel" then
          p.role = "renegade"
          rebel = true
          renegade = p
          room:broadcastProperty(p, "role")
        end
      end
    Buddy(room)
  end

  if renegade and ag%20 == 0 then
    room:changeMaxHp(renegade,1 )
      room:recover({
      who = renegade,
      num = 1,
      recoverBy = renegade,
      skillName = "奖励",
      })
  end
  --偶像生成
  if renegade and renegade.dead then
    addox(room)
    --drawInit(room,renegade,renegade.hp)
    renegade:drawCards(renegade.hp)
    moveSeats(room)
    room:addPlayerMark(renegade, MarkEnum.PlayerRemoved, 1)
    
  end
  
end


local  store

--年兽商店
local function ns_store(player)
  local room = player.room
  local n = room:getBanner("@tshu__coin") or 0
  local sp = {}
  local jg = {}
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  local lose = all - win
   if lose < 2 or room.settings.enableDeputy then
    table.insertIfNeed(sp,"tshujl__zhaoyun")
    table.insertIfNeed(jg,{"tshu_ns_no1"})
  end
  table.insertIfNeed(sp,"tshufd__nsfudai")
  table.insertIfNeed(jg,{"tshu_ns_no2"})
  local result = room:askForCustomDialog(player, "tshu_ns_store",
  "packages/tshu/qml/ChooseGeneralSkillsBox.qml", {
    sp, jg, 1, 1, "#ns_store-choice", true
  })
  if result and table.concat(json.decode(result)) ~= "" then
    if table.concat(json.decode(result)) == "tshu_ns_no1" then
      if n < 1200 then
        room:doBroadcastNotify("ShowToast", "“神赵云”不喜欢穷逼。")
      else
        room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 1200)
        zhaoyun(room,player)
        room:doBroadcastNotify("ShowToast", "购买成功，扣除1200张“天书残页”。")
        room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
        room:doBroadcastNotify("ShowToast", "★年兽商店：已为"..Fk:translate(player.general).."【将灵池】永久解锁将灵——“神赵云”！★")
        local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
        table.insertIfNeed(jl,"tshujl__zhaoyun")
        for _, s in ipairs(Fk.generals["tshujl__zhaoyun"].skills) do
          room.players[1]:broadcastSkillInvoke(s.name)
          break
        end
        room:setBanner("@&tshu__jl",jl)
        room:delay(500)
      end
    elseif table.concat(json.decode(result)) == "tshu_ns_no2" then
      room:doBroadcastNotify("ShowToast", "“年兽福袋”暂时缺货..")
    end
    ns_store(player)
  else
    store(player)
  end
end
Fk:loadTranslationTable{
  ["tshu_ns_no1"] = "1200残页",
  ["tshu_ns_no2"] = "30残页",
}
--天书商店
local function tshu_store(player)
  local room = player.room
  if player:getMark("manghe_lose-phase") > 0 then
    local bc = player:getMark("manghe_lose-phase")*math.random(10,30)
    room:setPlayerMark(player,"manghe_lose-phase",0)
    room:doBroadcastNotify("ShowToast", "“天书商店”补偿了"..bc.."张“天书残页”。")
    room:delay(300)
    room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) + bc)
  end
  local n = room:getBanner("@tshu__coin") or 0
  local ag = room:getBanner("@layers") or 0
  local sp = {"tshu__manghe","tshu__supermanghe","tianshus","tianshum","tshuchzhi","tshu__lshi","tshu__chsheng","tshu__addgen","tshu__zhixi","tshu__go"}
  if room:getBanner("@[:]tshu__gongskill") and room:getBanner("@[:]tshu__gongskill") ~= 0  then
    sp = {"tshu__gong","tshu__manghe","tshu__supermanghe","tianshus","tianshum","tshuchzhi","tshu__lshi","tshu__chsheng","tshu__addgen","tshu__zhixi","tshu__go"}
  end
  local all = table.simpleClone(sp)
  if (ag +2)%5 == 0 or (ag + 1)%5 == 0 then
    table.removeOne(sp,"tshu__jdu")
  end
  local mark = player:getTableMark("@[tshu__tianshu]")
  local tn = mark and #mark or 0
  if tn >= 20 then
    table.removeOne(sp,"tianshus")
    table.removeOne(sp,"tianshum")
  end
  local choice = room:askForChoice(player,sp,"tshu_store","tshu_store-ask",false,all)
  if choice == "tshu__gong" then
    if n < 2 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 2)
      room:doBroadcastNotify("ShowToast", "扣除2张“天书残页”交换公共技能库。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      gongskill(player)
    end
  elseif choice == "tshu__manghe" then
    if n < 20 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 20)
      room:doBroadcastNotify("ShowToast", "扣除20张“天书残页”购买“盲盒”一次。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      random(room,player)
    end
  elseif choice == "tshu__supermanghe" then
    if n < 50 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 50)
      room:doBroadcastNotify("ShowToast", "扣除50张“天书残页”购买“超级盲盒”一次。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      random2(room,player)
    end
  elseif choice == "tianshus" then
    if n < 40 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 40)
      room:doBroadcastNotify("ShowToast", "扣除40张“天书残页”增加一个天书技能。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      tianshu1(room,player,1,10)
    end
  elseif choice == "tianshum" then
    if n < 60 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 60)
      room:doBroadcastNotify("ShowToast", "扣除60张“天书残页”增加一个天书限定觉醒技。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      tianshu2(room,player,1,10)
    end
  elseif choice == "tshuchzhi" then
    if n < 30 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 30)
      room:doBroadcastNotify("ShowToast", "扣除30张“天书残页”重置一次天书技。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      remove(room,player,1)
      tianshu1(room,player,1,5)
    end
  elseif choice == "tshu__lshi" then
    if n < 40 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 40)
      room:doBroadcastNotify("ShowToast", "扣除40张“天书残页”购买一个临时技能。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      lshi1(room,player,1,10)
    end
  elseif choice == "tshu__chsheng" then
    if n < 20 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 20)
      room:doBroadcastNotify("ShowToast", "扣除20张“天书残页”进行一次“重生”。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      room:broadcastPlaySound("./packages/shzl/audio/skill/niepan2")
      room:doBroadcastNotify("ShowToast", "重生！！！")
      local deputyHp = player:getMark("@deputyHp")
      player:setCardUseHistory("")
      player:setSkillUseHistory("")
      local mark = player:getTableMark("@[tshu__tianshu]")
      local nmark = {"tshujl__miaolvlingqi","@tshu_lv","@deputyHp","tongling","wangzhe","juejie","chaoyuan","shengti","shuangsheng","tshujl__chuangshi_choose","@[tshu__tianshu]","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@&tshu__jlmark","tshujl__nianzhugeliang"}
      local jl = room:getBanner("@&tshu__jl")
      table.insertTable(nmark,jl)
      for name, _ in pairs(player.mark) do
        if not table.contains(nmark,name) then
          room:setPlayerMark(player, name, 0)
        end
      end
      player:clearPiles()
      player:reset()
      --补技能
      for _, s in ipairs(mark) do
        if not player:hasSkill(s) then
          room:handleAddLoseSkills(player,s,nil,true)
        end
      end
      room:resumePlayerArea(player, player.sealedSlots)
      room:revivePlayer(player, false)
      restart(player)
      room:setPlayerMark(player,"@deputyHp",deputyHp)
    end
  elseif choice == "tshu__jdu" then
    if n < 10 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 10)
      room:doBroadcastNotify("ShowToast", "扣除10张“天书残页”增加一关进度。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      local ag = room:getBanner("@layers") or 0
      local m = 1
      local n2 = 0
      for _, p in ipairs(room.players) do
        if p.role == "rebel" then
          n2 = n2 + 1
        end
      end
      ag = ag + 1
      local Allgenerals = room:getBanner("@&Allgenerals")
      if #room.general_pile < n then
        local genss = room:getBanner("@&Allgenerals")
        if #genss > 0 then
          room:returnToGeneralPile(genss)
        end
      end
      local gb = room:getNGenerals(n)
      for _, g in ipairs(gb) do
        table.insertIfNeed(Allgenerals,g)
      end
      room:setBanner("@&Allgenerals", Allgenerals)
    end
  elseif choice == "tshu__addgen" then
    if n < 10 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 10)
      room:doBroadcastNotify("ShowToast", "扣除10张“天书残页”选择一次武将。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      addGenerals(player)
    end
  elseif choice == "tshu__zhixi" then
    if n < 20 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 10)
      room:doBroadcastNotify("ShowToast", "扣除20张“天书残页”购买技能〖止息〗。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      room:handleAddLoseSkills(player,"ty__zhixi",nil,true)
    end
  end
  if choice == "tshu__go" then
    store(player)
  else
    tshu_store(player)
  end
end
Fk:loadTranslationTable{
  ["tshu_store-ask"] = "选择要购买的商品",
  ["tshu__gong"] = "交换公共技能:2残页",
  ["tshu__manghe"] = "盲盒：20残页",
  ["tshu__supermanghe"] = "超级盲盒：50残页",
  ["tianshus"] = "小天书技：40残页",
  ["tianshum"] = "大天书技：60残页",
  ["tshuchzhi"] = "重置天书：30残页",
  ["tshu__lshi"] = "临时技能：30残页",
  ["tshu__chsheng"] = "重生：20残页",
  ["tshu__jdu"] = "进度+1：10残页",
  ["tshu__addgen"] = "增加武将：10残页",
  ["tshu__zhixi"] = "技能〖止息〗：20残页",
  ["tshu__go"] = "返回",
  ["tshu__goumai"] = "购买",
  ["tshu__nogoumai"] = "返回商店",

}
--庆典商店
local function tshu_qd_store(player)
  local room = player.room
  local n = room:getBanner("@tshu__coin") or 0
  local ag = room:getBanner("@layers") or 0
  local sp = {"tshu_qd__manghe","tshu_qd__supermanghe","tshu__go"}
  local qd = true
  local all = table.simpleClone(sp)
  local choice = room:askForChoice(player,sp,"tshu_qd_store","tshu_store-ask",false,all)
  if choice == "tshu_qd__manghe" then
    if n < 12 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 12)
      room:doBroadcastNotify("ShowToast", "扣除12张“天书残页”购买“庆典盲盒”一次。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      random(room,player,qd)
    end
  elseif choice == "tshu_qd__supermanghe" then
    if n < 30 then
      room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    else
      room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - 30)
      room:doBroadcastNotify("ShowToast", "扣除30张“天书残页”购买“超级庆典盲盒”一次。")
      room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
      random2(room,player,qd)
    end
  end
  if choice == "tshu__go" then
    store(player)
  else
    tshu_qd_store(player)
  end
end
Fk:loadTranslationTable{
  ["tshu_qd_store"] = "庆典商店",
  ["tshu_qd__manghe"] = "庆典盲盒：12残页",
  ["tshu_qd__supermanghe"] = "超级庆典盲盒：30残页",

}
--卡牌商店
local gocards

local function cards_store(player)
  local room = player.room
  local cardType = { 'basic', 'trick', 'equip' ,'tshu__cancel2'}
  local cardTypeName = room:askForChoice(player, cardType, "卡牌商店","请选择要购买的卡牌类型")
  if cardTypeName ~= "tshu__cancel2" then
    local card_types = {Card.TypeBasic, Card.TypeTrick, Card.TypeEquip}
    cardType = card_types[table.indexOf(cardType, cardTypeName)]
    gocards(player,cardType)
  else
    --store(player)
  end
end

gocards =  function(player,Type)
  local room = player.room
    local blacklist = {"crossbow","indulgence","wd_rice","diy_restart"}
    local allCardIds = Fk:getAllCardIds()
    local allCardMapper = {}
    local allCardNames = {}
    for _, id in ipairs(allCardIds) do
      local card = Fk:getCardById(id)
      if not card.is_derived and not table.contains(blacklist, card.name) and card.type == Type 
      and not (room:getCardArea(id) == Card.PlayerHand or room:getCardArea(id) == Card.PlayerEquip or room:getCardArea(id) == Card.PlayerJudge)  then
        if allCardMapper[card.name] == nil then
          table.insert(allCardNames, card.name)
        end

        allCardMapper[card.name] = allCardMapper[card.name] or {}
        table.insert(allCardMapper[card.name], id)
      end
    end
    table.insert(allCardNames, "tshu__cancel2")

    if #allCardNames == 0 then
      return
    end

    local cardName = room:askForChoice(player, allCardNames, "卡牌商店")
    local toGain -- = room:printCard(cardName, Card.Heart, 1)
    if cardName == "tshu__cancel2" then
      cards_store(player)
    elseif #allCardMapper[cardName] > 0 then
      toGain = allCardMapper[cardName][math.random(1, #allCardMapper[cardName])]
      local car = Fk:getCardById(toGain)
      local n = 3
      if car.type == Card.TypeBasic then
        n =1
      elseif car.type == Card.TypeTrick then
        n = 2
      elseif car.type == Card.TypeEquip then
        n = 3
      end
      local shop = {"花费"..n.."张“天书残页”购买","tshu__nogoumai"}
      local shop2 = table.simpleClone(shop)
      if (room:getBanner("@tshu__coin") or 0) < n then
        table.removeOne(shop,"花费"..n.."张“天书残页”购买")
      end
      if room:askForChoice(player,shop,"购买确认","是否花费"..n.."张“天书残页”购买一张"..Fk:translate(cardName).."？",false,shop2) == "花费"..n.."张“天书残页”购买" then
        if (room:getBanner("@tshu__coin") or 0) < n then
          room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
          gocards(player,Type)
        else
          room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - n)
          room:doBroadcastNotify("ShowToast", "扣除"..n.."张“天书残页”购买一张"..Fk:translate(cardName))
          room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
          room:obtainCard(player, toGain, true, fk.ReasonPrey)
        end
      else
        gocards(player,Type)
      end
    end
  
end
--刷怪检测
local function doboss(player)
  local room = player.room
  local yes = false
  for _, p in ipairs(room.alive_players) do
    if p.role == "rebel" then
      yes = true
    end
  end
  if yes then 
    room:doBroadcastNotify("ShowToast", "请击杀所有敌人。")
    store(player)
  elseif room.current:insideExtraTurn() then
    room:doBroadcastNotify("ShowToast", "请结束额外回合。")
    store(player)
  elseif room:getBanner("tshu__boss_do") and room:getBanner("tshu__boss_do") == 1 then
    room:setBanner("tshu__boss_do",0)
    room:doBroadcastNotify("ShowToast", "检测完成，开始进入下一层。")
    canreward(room)
  else
    room:doBroadcastNotify("ShowToast", "已中止当前所有结算，请于下回合继续晋层")
    room:setBanner("tshu__boss_do",1)
    room.logic:breakTurn()
  end
end
--跳层


--解锁层数
local function upsave(room,p)
  local self = room
  if not self.game_started then return end
      local id = p.id
      local general = p.general
      local mode = self.settings.gameMode

      if p.id > 0 then
        local all = p._splayer:getGameData():at(0)
        local win = p._splayer:getGameData():at(1)
        local lose = all - win
        if p.role == "lord" or p.role == "loyalist" then
            if  lose >= 2 and lose < 12  then
              self.room:updateWinRate(id, general, mode, 2, p.dead)
            end
        end
  end
end

local function shoplay(player,layers)
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  --已解锁层数
  local lose = all - win - 2
  if lose >= 10 then return end
  local ag =  player.room:getBanner("@layers") or 0
  local ns = ag//100
  if ns > lose then
  local n = 1000
  local room = player.room
  local choice = room:askForChoice(player,{"果断解锁","还是算了"},"直通车","是否愿意花费 "..n.." 张“天书残页”永久解锁<font color='red'>神赵直通车</font> "..layers.."层 的记录？",false,{"果断解锁","还是算了"})
  --local choice = room:askForCustomDialog(player,"神赵直通车","packages/lang/qml/DialogChoiceBox.qml",{"神赵直通车","是否愿意花费 "..n.." 张“天书残页”永久解锁<font color='red'>神赵直通车</font> "..layers.."层 的记录？",{"果断解锁","还是算了"},"tshujl__zhaoyun"})
  if choice == "果断解锁" then 
  if (room:getBanner("@tshu__coin") or 0) < 1000 then
    room:doBroadcastNotify("ShowToast", "购买失败，“天书残页”不足。")
    return false
  else
    room:setBanner("@tshu__coin",(room:getBanner("@tshu__coin") or 0) - n)
    room:doBroadcastNotify("ShowToast", "已扣除"..n.."张“天书残页”为 "..Fk:translate(player.general).." 永久解锁<font color='red'>神赵直通车</font>第 "..layers.." 层记录。")
    room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__shop")
    upsave(room,player)
    return true
  end
  end
  end
end
--询问购买
local function slay(player)
  local room = player.room
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  --已解锁层数
  local lose = all - win - 2
  if lose >= 10 then return end
  --当前层数
  local ag =  room:getBanner("@layers") or 0
  local n = ag//100
  if n > lose then
    local layers = (lose + 1)*100
    local yes = shoplay(player,layers)
  end
end

local function layshop(player)
  local room = player.room
  local sslay = "升级直通车"
  local lay1 = "第99层"
  local lay2 = "第199层"
  local lay3 = "第299层"
  local lay4 = "第399层"
  local lay5 = "第499层"
  local lay6 = "第599层"
  local lay7 = "第699层"
  local lay8 = "第799层"
  local lay9 = "第899层"
  local lay10 = "第999层"
  local back = "返回"
  local sp = "第150层"
  local shops = {sslay,lay1,lay2,lay3,lay4,lay5,lay6,lay7,lay8,lay9,lay10,back}
  local canshops = {}
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  --已解锁层数
  local lose = all - win - 2
  local ag =  room:getBanner("@layers") or 0
  local n = (ag+2)//100
  if lose < n and not room.settings.enableDeputy  then
    table.insertIfNeed(canshops,sslay)
  end
  if lose > n then
    for i = 1, 10, 1 do
      if n < i and lose >= i then
        table.insertIfNeed(canshops,shops[i + 1])
      end
    end
  end
  table.insertIfNeed(canshops,back)
  if player.id == 00000 or player.id == "0000000" then
    table.insertIfNeed(shops,sp)
    table.insertIfNeed(canshops,sp)
  end
  local goug = room:askForCustomDialog(player,"神赵直通车","packages/tshu/qml/DialogChoiceBox.qml",{"神赵直通车","选择要通过 <font color='red'>神赵直通车</font> 前往的层数,使用<font color='red'>神赵直通车</font>后将无法解锁<font color='purple'>5~200层</font>的将灵：",canshops,"tshujl__zhaoyun"})
  local gou
  if goug ~= "" then
    gou = json.decode(goug)
  end
  --local gou = room:askForChoice(player,canshops,"神赵直通车","选择要通过 <font color='red'>神赵直通车</font> 前往的层数,使用<font color='red'>神赵直通车</font>后将无法解锁<font color='purple'>5~200层</font>的将灵",false,shops)
  if gou == "升级直通车" then
    slay(player)
    layshop(player)
  elseif gou == "返回" then
    store(player)
  else
    local num 
      if gou == "第99层" then
        num = 99
      elseif gou == "第199层" then
        num = 199
      elseif gou == "第299层" then
        num = 299
      elseif gou == "第399层" then
        num = 399
      elseif gou == "第499层" then
        num = 499
      elseif gou == "第599层" then
        num = 599
      elseif gou == "第699层" then
        num = 699
      elseif gou == "第799层" then
        num = 799
      elseif gou == "第899层" then
        num = 899
      elseif gou == "第999层" then
        num = 999
      elseif gou == "第150层" then
        num = 150
      end
    if num ~= nil then
      jump(player,num)
      layshop(player)
    end
  end
end

--商店
store = function (player)
  local room = player.room
  local n = room:getBanner("@tshu__coin") or 0
  local all = player._splayer:getGameData():at(0)
  local win = player._splayer:getGameData():at(1)
  local lose = all - win
  local choices = {"tshu_boss_do","tshu_zy_store","tshu_ns_store","tshu_store","tshu_cards_store","tshu__cancel"}
  if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
    table.insert(choices,3,"tshu_qd_store")
  end
  local als = table.simpleClone(choices)
  if lose <= 0 then
    table.removeOne(choices,"tshu_ns_store")
  end
  if lose <= 1 then
    table.removeOne(choices,"tshu_zy_store")
  end
  local choice = room:askForChoice(player,choices,"tshu_shop","tshu_shop-ask",false,als)
  if choice == "tshu_ns_store" then
    ns_store(player)
  elseif choice == "tshu_zy_store" then
    layshop(player)
  elseif choice == "tshu_store" then
    tshu_store(player)
  elseif choice == "tshu_qd_store" then
    tshu_qd_store(player)
  elseif choice == "tshu_cards_store" then
    --room:doBroadcastNotify("ShowToast", "“卡牌商店”暂未开业..")
    cards_store(player)
    store(player)
  elseif choice == "tshu_boss_do" then
    doboss(player)
  end
end
Fk:loadTranslationTable{
  ["tshu_shop"] = "商店",
  ["@tshu__coin"] = "天书残页",
  ["tshu_boss_do"] = "层数晋级",
  ["tshu_store"] = "天书商店",
  ["tshu_cards_store"] = "卡牌商店",
  ["tshu_ns_store"] = "年兽商店",
  ["#ns_store-choice"] = "年兽商店",
  ["tshu_zy_store"] = "神赵直通车",
  ["tshu_shop-ask"] = "选择要进入的商店",
  ["tshu__cancel"] = "退出",
  ["tshu__cancel2"] = "返回",
  ["@[:]tshu__gongskill"] = "公共技能库",
}


--[[
--暂停
local function ice(room)
  local lord = {}
  for _, p in ipairs(room.players) do
    if p.role == "lord" or p.role == "loyalist" then
      table.insertIfNeed(lord,p)
    end
  end
  for _, p in ipairs(lord) do
    local choices = {"tshu__inice","tshu__noice"}
    p.request_data = json.encode({choices, choices, "tshu__ice&", "#inice-choice",false})
    --p.default_reply = "tshu__inice"
  end
  room:notifyMoveFocus(room.alive_players,"tshu__ice&")
  room:doBroadcastRequest("AskForChoice", lord)
  local noice = false
  for _, p in ipairs(lord) do
    local choice
    if p.reply_ready then
      choice = p.client_reply
    else
      p.client_reply = "tshu__inice"
      choice = "tshu__inice"
    end
    if choice == "tshu__noice" then
      noice = true
    end
  end
  if not noice then
    ice(room)
  end
end
Fk:loadTranslationTable{
  ["tshu__inice"] = "继续暂停",
  ["tshu__noice"] = "取消暂停",
  ["#inice-choice"] = "暂停选择",
  ["#tshu__ice-quest"] = "暂停",

}]]
--切换武将
local change = fk.CreateActiveSkill{
  name = "tshu__change&",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = "你可以翻面，然后从所持武将库里选择一名其他武将替换当前主将",
  can_use = function(self, player)
      return player.faceup and player:getMark("changeago") == 0 and Fk:currentRoom():getBanner("@&GetGenerals") and #Fk:currentRoom():getBanner("@&GetGenerals") > 0  and player.deputyGeneral ~= "ycylh__linghun"
  end,
  
  
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local gen = player.general
    local Get2 = table.simpleClone(room:getBanner("@&GetGenerals"))
    local mark =  player:getTableMark("@[tshu__tianshu]")
      local ggg = room:askForGeneral(player,Get2,1,false)
      if not table.contains(Get2,ggg) then
        ggg = table.random(Get2,1)
      end

      if ggg and ggg ~= "" and ggg[1] and ggg[1] ~= "" then
        local deputyHp = player:getMark("@deputyHp")
        player:setCardUseHistory("")
    player:setSkillUseHistory("")
    local nmark = {"tshujl__miaolvlingqi","@tshu_lv","@deputyHp","tongling","wangzhe","juejie","chaoyuan","shengti","shuangsheng","@[tshu__tianshu]","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@&tshu__jlmark"}
    local jl = room:getBanner("@&tshu__jl")
    table.insertTable(nmark,jl)
    for name, _ in pairs(player.mark) do
      if not table.contains(nmark,name) then
        room:setPlayerMark(player, name, 0)
      end
    end
    player:clearPiles()
    player:reset()
        local noto_rm = table.filter(player.player_skills, function(s)
          return not s.attached_equip and s ~= self and not table.contains(mark,s.name) and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
        end)
        room:handleAddLoseSkills(player, table.concat(
      table.map(noto_rm, function(s) return "-" .. s.name end), "|"), nil, true)
      --补技能
      for _, s in ipairs(mark) do
        if not player:hasSkill(s) then
          room:handleAddLoseSkills(player,s,nil,true)
        end
      end
      
      if player.deputyGeneral ~= "" then
      if #Fk.generals[player.deputyGeneral].skills > 0 then
    for _,s in ipairs(Fk.generals[player.deputyGeneral].skills) do
      room:handleAddLoseSkills(player,s.name,nil,true)
    end
    end
    if #Fk.generals[player.deputyGeneral].other_skills > 0 then
    for _,s in ipairs(Fk.generals[player.deputyGeneral].other_skills) do
      room:handleAddLoseSkills(player,s,nil,true)
    end
    end
    end
    room:resumePlayerArea(player, player.sealedSlots)
      
        table.removeOne(Get2,ggg)
        table.insertIfNeed(Get2,gen)
        room:setBanner("@&GetGenerals",Get2)
        room:changeHero(player, ggg, false, false, true,true)
        room:revivePlayer(player, false)
        room:setPlayerMark(player,"@[tshu__tianshu]",mark)
        room:setPlayerProperty(player, "kingdom", Fk.generals[ggg].kingdom)
        room:askForChooseKingdom({player})
        room:setPlayerProperty(player, "hp", Fk.generals[ggg].hp)
        room:setPlayerMark(player,"@deputyHp",deputyHp)
        restart(player)
      if player.faceup then
        player:turnOver()
      end
      room:setPlayerMark(player,"changeago",1)
    end
  end,
}
Fk:addSkill(change)

--更换将灵
local changejl = fk.CreateActiveSkill{
  name = "tshu__changejl&",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = "★放生现在持有的将灵，然后从【将灵池】中重新领养一只将灵。",
  can_use = function(self, player)
      return  player:getMark("changejlago") == 0 and Fk:currentRoom():getBanner("@&tshu__jl") and #Fk:currentRoom():getBanner("@&tshu__jl") > 0 
  end,
  
  
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
    local skills = {}
    local jlk = {"tshujl__nianlvbu","tshujl__miaolvlingqi","tshujl__zhugeguo","tshujl__lingjv","tshujl__zhouyu","tshujl__caoying","tshujl__nianshou","tshujl__xiaosha","tshujl__guansuo","tshujl__caochun","tshujl__guanyu","tshujl__zhaoxiang","tshujl__zhaoyun","tshujl__zhouyi","tshujl__nianzhugeliang","tshujl__sajia"}
    for _, s in ipairs(jlk) do
      if player:getMark(s) > 0 then
        table.removeOne(jl,s)
        room:setPlayerMark(player,s,0)
      end
    end
    room:setPlayerMark(player,"@&tshu__jlmark",0)
    local all = player._splayer:getGameData():at(0)
    local win = player._splayer:getGameData():at(1)
    local lose = all - win
    if  win < 1 then
      table.removeOne(jl,"tshujl__caoying")
    end
    if  win < 2 then
      table.removeOne(jl,"tshujl__guansuo")
      table.removeOne(jl,"tshujl__zhouyi")
    end
    if  win < 3 then
      table.removeOne(jl,"tshujl__caochun")
    end
    if  win < 4 then
      table.removeOne(jl,"tshujl__nianzhugeliang")
    end
    if  win < 5 then
      table.removeOne(jl,"tshujl__miaolvlingqi")
      table.removeOne(jl,"tshujl__nianlvbu")
    end
    if  lose < 1 then
      table.removeOne(jl,"tshujl__nianshou")
    end
    if  lose < 2 then
      table.removeOne(jl,"tshujl__zhaoyun")
    end
    for _, s in ipairs(jl) do
      if s == "tshujl__nianzhugeliang" then
        table.insert(skills,{"tshujl__nianzhuge_choice"})
      elseif s == "tshujl__miaolvlingqi" then
        table.insert(skills,{"tshujl__miaolvlingqi_choice"})
      elseif s == "tshujl__nianlvbu" then
        table.insert(skills,{"tshujl__nianlvbu_choice"})
      else
        table.insert(skills,{s})
      end
    end
    local result = room:askForCustomDialog(player, "tshu__jl",
  "packages/tshu/qml/ChooseGeneralSkillsBox.qml", {
    jl, skills, 1, 1, "#jl-choice", true
  })
  if result and Fk:translate(table.concat(json.decode(result))) ~= "" then
    local j = json.decode(result)
    local choice = table.concat(j)
    if table.concat(j) == "tshujl__nianzhuge_choice" then
      choice = "tshujl__nianzhugeliang"
    elseif table.concat(j) == "tshujl__nianlvbu_choice" then
      choice = "tshujl__nianlvbu"
    elseif table.concat(j) == "tshujl__miaolvlingqi_choice" then
      choice = "tshujl__miaolvlingqi"
    end
    room:doBroadcastNotify("ShowToast","★"..Fk:translate(player.general).."已领养将灵——".."“"..Fk:translate(choice).."”")
    room:notifySkillInvoked(player,choice,"drawcard")
    for _, s in ipairs(Fk.generals[choice].skills) do
      player:broadcastSkillInvoke(s.name)
      break
    end
    room:setPlayerMark(player,choice,1)
    room:setPlayerMark(player,"@&tshu__jlmark",{choice})
    room:setPlayerMark(player,"changejlago",1)
  end
  end,
}
Fk:addSkill(changejl)

local stores = fk.CreateActiveSkill{
  name = "tshu__store&",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = "逛一逛贵得要死的商店。",
  can_use = function(self, player)
      return  true
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    store(player)
  end,
}
Fk:addSkill(stores)

--[[
local ices = fk.CreateActiveSkill{
  name = "tshu__ice&",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = "不离开服务器的情况下，进行无限烧条以实现“暂停”效果。",
  can_use = function(self, player)
      return  true
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    ice(room)
  end,
}
Fk:addSkill(ices)
]]

local tshu_rule = fk.CreateTriggerSkill{
  name = "#tshu_rule",
  priority = 0.001,
  refresh_events = {fk.DrawInitialCards,fk.EnterDying,fk.GameOverJudge, fk.BuryVictim, fk.GameStart,fk.RoundStart,fk.TurnStart,fk.TurnEnd,fk.DamageCaused,fk.RoundEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.TurnEnd or event == fk.DamageCaused then
      return target == player  and player.role == "rebel"
    elseif event == fk.EventAcquireSkill then
      local zb = {"cheat","control","change_hero","damage_maker","test_zhenggong"}
      return target == player and table.contains(zb,data.name)
    elseif event == fk.EnterDying then
      return target == player and player.role == "rebel" and player:getMark("tshu_fuhuo1-round") == 0 and player.room:getBanner("@layers") and player.room:getBanner("@layers") >= 99
    else
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local body
    local nmark = {"tshujl__miaolvlingqi","@tshu_lv","@deputyHp","tongling","wangzhe","juejie","chaoyuan","shengti","shuangsheng","@[tshu__tianshu]","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","manghe_lose-phase","@&tshu__jlmark",}
    local gjl = room:getBanner("@&tshu__jl")
    table.insertTable(nmark,gjl)
    if event == fk.EnterDying then
      local n = math.min(player.maxHp//2,1)
      player.room:setPlayerMark(player,"tshu_fuhuo1-round",1)
      player.hp = n
      room:doBroadcastNotify("ShowToast", "<font color='green'>天书守护</font>：100层及以上的敌人每轮首次进入<font color='red'>濒死状态</font>时将体力恢复至体力上限的一半。")
      room:broadcastProperty(player, "hp")
      room:delay(200)
    elseif event == fk.BuryVictim or event == fk.GameOverJudge then
      body = room:getPlayerById(data.who)
      if body:getMark("tshujl__sajia") > 0 and body:usedSkillTimes("tshujl__matai", Player.HistoryGame) == 0 then
        table.insertIfNeed(nmark,"tshujl__chuangshi_choose")
        table.insertIfNeed(nmark,"tshujl__chuangshi")
      end
    end
    if event == fk.DrawInitialCards then
      if player.role == "renegade" then
        data.num = 5
      else
        data.num = 5
      end
    elseif event == fk.EventAcquireSkill then
      for _, s in ipairs({"cheat","control","change_hero","damage_maker","test_zhenggong"}) do
        room:handleAddLoseSkills(player,"-"..s,nil,true)
      end
    elseif event == fk.GameOverJudge then
      local tst = {"emotest","mouxusheng"}
      room:setTag("SkipGameRule", true)
      for _, p in ipairs(room.alive_players) do
        if p.role == "lord" or p.role == "loyalist" then
          if table.contains(tst,p.general) or table.contains(tst,p.deputyGeneral) then
            room:doBroadcastNotify("ShowToast", "出现了不该出现的角色")
            room:gameOver("")
          end
        end
      end
      if body:getMark("tshujl__sajia") > 0 and body:usedSkillTimes("tshujl__matai", Player.HistoryGame) == 0 then
        return
      end
      local nowin1 = false
      for _, p in ipairs(room.alive_players) do
        if p.role == "lord" or p.role == "loyalist" then
          nowin1 = true
        end
        if nowin1 then break end
      end
      if (body.role == "lord" or body.role == "loyalist") and nowin1 then return end
      if  (body.role == "lord" or body.role == "loyalist") and room:getBanner("@&GetGenerals") and #room:getBanner("@&GetGenerals") >= 1 then return end
      if  body.role == "renegade"  then  return end
      local nowin = false
      for _, p in ipairs(room.alive_players) do
        if p.role == "rebel" then
          nowin = true
        end
        if nowin then break end
      end
      if nowin and body.role == "rebel" then 
        return 
      end
      if body.role == "rebel"   then 
        return 
      end
      if body.role == "rebel" then
        room:doBroadcastNotify("ShowToast", "恭喜！你通关啦！")
        room:gameOver("lord")
      else
        room:doBroadcastNotify("ShowToast", Fk:translate("#tshu__lordwin"))
        room:gameOver("rebel")
      end
      
      return true
    elseif event == fk.GameStart then
      local n = #room.players
      local bots_t = {}
      local players_t = {}
      for i = 1, n do
        local p = room.players[i]
        if p.id < 0 then
          table.insert(bots_t,{p.id,i})
        end
        if p.id > 0 then
          table.insert(players_t,{p.id,i})
        end
      end
      
      --[[
      if room.settings.enableFreeAssign then
        room:doBroadcastNotify("ShowToast", "不支持自由选将噢~")
        room:gameOver(player.role)
        return
      end]]
      if (#players_t > 1 and n == 3) or (#players_t > 2 and n == 4) or (#players_t > 2 and n == 5) or (#players_t > 3 and n == 6) or (#players_t > 3 and n == 7) or (#players_t > 4 and n == 8) or (#players_t > 4 and n == 9) or (#players_t > 5 and n == 10)then
        room:doBroadcastNotify("ShowToast", "请保证真人不超过房间人数一半。")
        room:gameOver("")
        return
      end
      local black3 = {"zuoci","ol_ex__zuoci","jbsao__wuyaowang","jbs_sairen","zhaoxiang","os__zhaoxiang","ol_ex__zuoci"}
      for _, p in ipairs(room.players) do
        if p.role ~= "renegade" and (Fk.generals[p.general].package.extensionName == "tshu" or p.general == "mouxusheng"  ) then
          room:doBroadcastNotify("ShowToast", "请不要选择天书工作人员")
          room:gameOver("")
        end
        if p.role ~= "renegade" and table.contains(black3,p.general)   then
          room:doBroadcastNotify("ShowToast", "禁止选择挂壁武将")
          room:gameOver("")
        end
        
        --[[
        if Fk.generals[p.general].package.extensionName == "ycy" then
          room:doBroadcastNotify("ShowToast", "请不要选择来自异次元的武将")
          room:gameOver("")
        end]]
      end
      moveSeats(room)
      for _, p in ipairs(room.players) do
        if p.role == "renegade" then
          room:addPlayerMark(p, MarkEnum.PlayerRemoved, 1)
          --room:killPlayer({ who = p.id })
        end
        if p.id == 000 or  p.id == "799" or p.id == 799 then
          local win = p._splayer:getGameData():at(1)
          if  win == 3 then
            local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
            table.insertIfNeed(jl,"tshujl__nianzhugeliang")
            room:setBanner("@&tshu__jl",jl)
            nianzhuge(room,p)
            room:doBroadcastNotify("ShowToast", "★补发成功，将灵池已永久解锁将灵“念·诸葛亮”！★")
            room:delay(500)
          end
        end
      end
      if   room.settings.enableDeputy then
         room:doBroadcastNotify("ShowToast", "已开启副将按钮，进入体验模式。")
      end
      room:delay(500)
      room:doBroadcastNotify("ShowToast", "可以观看队友手牌噢~")
      room:doBroadcastNotify("ShowToast", "★第一个将灵目标————通关第5层！")
      
      room.logic:trigger("fk.Debut", player, player.general, false)
      room.logic:trigger("fk.Debut", player.next, player.general, false)


      ----电脑死亡
    elseif event == fk.BuryVictim and body.role == "rebel" then
      room:setTag("SkipGameRule", true)
      
      room:throwCard(body.player_cards[Player.Hand], "", body)
      if body:getMark("tshujl__sajia") > 0 and body:usedSkillTimes("tshujl__matai", Player.HistoryGame) == 0 then
        return
      end
      body:bury()
      local ag = room:getBanner("@layers") or 0
      if ag >= 199 and body.hp > 0 and body.maxHp > 0 then
        room:doBroadcastNotify("ShowToast", "〖<font color='red'>天书护佑</font>〗：200层及以上的敌人无法受到<font color='blue'>即死</font>效果。")
        room:revivePlayer(body,true)
        body.hp = body.maxHp
        room:broadcastProperty(body, "hp")
        room:delay(500)
        return
      end
      local tgodboss = {"tshugod__jiaxu1","tshugod__jiaxu2","tshugod__kuafu","tshugod__shaohao","tshugod__xuannv","tshugod__hanba","tshugod__caoe","tshugod__taoshen","tshugod__hebo","tshugod__yuershen","tshugod__yanluowang","buqun__ailing"}
      if ag > 10 and math.random(1,5) == 1 then
        local n = math.random(1,3) + math.random(0,2)*(ag//20)
        if table.contains(tgodboss,body.general) then
            n = n*2
        end
        if math.random(1,2) == 1 then
          local ns = false
          for _, p in ipairs(room.alive_players) do
            if p:getMark("tshujl__nianshou") > 0 then
              ns = true
              break
            end
          end
          if ns then
            room:doBroadcastNotify("ShowToast", "“年兽”让天书残页翻了一倍")
            n = n*2
          end
        end
          if room:getBanner("@[:]sday_qdian") and room:getBanner("@[:]sday_qdian") == "sday_qdian" then
            n = n*2
            room:doBroadcastNotify("ShowToast", "庆典日！！！")
          end
          
        room:doBroadcastNotify("ShowToast", "击杀掉落"..n.."张“天书残页”")
        room:setBanner("@tshu__coin", (room:getBanner("@tshu__coin") or 0) + n)
        room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__canye")
        room:delay(300)
      end
      local ss = {"tshuss__qinglong","tshuss__zhuque","tshuss__baihu","tshuss__xuanwu"}
      if table.contains(ss,body.general) then
        local a = math.random(1,10)
        if a <= 7 then
          local n = math.random(1,10)
          room:doBroadcastNotify("ShowToast", "神兽馈赠：获得"..n.."张“天书残页”")
          room:delay(300)
          room:setBanner("@tshu__coin", (room:getBanner("@tshu__coin") or 0) + n)
          room:broadcastPlaySound("./packages/tshu/audio/mp3/tshu__canye")
          room:delay(300)
        elseif a <= 9 then
          room:doBroadcastNotify("ShowToast", "神兽馈赠：一个额外的天书技能")
          room:delay(500)
          for _, p in ipairs(room.players) do
            if p.role == "lord" or p.role == "loyalist" then
              tianshu1(room,p,1,10)
            end
          end
        elseif a <= 10 then
          room:doBroadcastNotify("ShowToast", "神兽馈赠：重置技能次数")
          room:delay(300)
          for _, p in ipairs(room.players) do
            if p.role == "lord" or p.role == "loyalist" then
              p:setSkillUseHistory("")
            end
          end
        end
      end
      if not room.settings.enableDeputy and (ag + 1)%100 == 0 and  table.contains(tgodboss,body.general) and data.damage and data.damage.from then
        local killer = data.damage.from
        if not killer.dead and killer.id > 0 and killer:getMark("tshujl__miaolvlingqi") > 0 then
          room:doBroadcastNotify("ShowToast", "奖励一枚<font color='red'>“吕家荣耀”</font>")
          room:delay(500)
          room:addPlayerMark(killer,"@tshu_lv",1)
          if killer:getMark("@tshu_lv") >= 5 then
            local win = killer._splayer:getGameData():at(1)
            if  win == 4 then
            local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
            table.insertIfNeed(jl,"tshujl__miaolvlingqi")
            table.insertIfNeed(jl,"tshujl__nianlvbu")
            room:setBanner("@&tshu__jl",jl)
            lvbu(room,killer)
            room:doBroadcastNotify("ShowToast", "★已为 "..Fk:translate(killer.general).." 将灵池永久解锁将灵“喵·吕玲绮”与“念·吕布”！★")
            room:delay(500)
            room:setPlayerMark(killer,"@tshu_lv",0)
            end
          end
        end
      end
      local nowin = false
      for _, p in ipairs(room.alive_players) do
        if p.role == "rebel" then
          nowin = true
        end
        if nowin then break end
      end
      if nowin then
        return
      else
        body:bury()
        if math.random(10) == 1 then
          room:setBanner("tshuss",1)
        else
          room:setBanner("tshuss",0)
        end
        canreward(room)
      end
      
    elseif event == fk.BuryVictim and body.role == "renegade" then
      room:doBroadcastNotify("ShowToast", "你真该死啊")
      room:delay(300)
      if body.general == "tshuox__xiaosha" and not table.contains(room:getBanner("@&tshu__jl"),"tshujl__xiaosha") then
        local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
        table.insertIfNeed(jl,"tshujl__xiaosha")
        room:doBroadcastNotify("ShowToast", "★隐藏奖励：【将灵池】已解锁将灵——“小杀”！")
        for _, s in ipairs(Fk.generals["tshujl__xiaosha"].skills) do
            room.players[1]:broadcastSkillInvoke(s.name)
            break
        end
        room:setBanner("@&tshu__jl",jl)
        room:delay(300)
      end
      return
      ---玩家死亡换将
    elseif event == fk.BuryVictim and (body.role == "lord" or body.role == "loyalist")  then
      room:setTag("SkipGameRule", true)
      if not table.contains(gjl,"tshujl__guanyu") then
        room:setBanner("tshujl__guanyu",(room:getBanner("tshujl__guanyu") or 0) + 1)
        if (room:getBanner("tshujl__guanyu") or 0) == 10 then
          room:setBanner("tshujl__guanyu",0)
          local jl = table.simpleClone(room:getBanner("@&tshu__jl"))
          table.insertIfNeed(jl,"tshujl__guanyu")
          room:doBroadcastNotify("ShowToast", "★死亡10次，【将灵池】已解锁将灵——“神关羽”！")
          for _, s in ipairs(Fk.generals["tshujl__guanyu"].skills) do
              room.players[1]:broadcastSkillInvoke(s.name)
          end
          room:setBanner("@&tshu__jl",jl)
          room:delay(300)
          end
      end
      local deputyHp = body:getMark("@deputyHp")
      if deputyHp <= 0 then
        room:changeHero(body,"",false,true,false,true)
      end
      body:setCardUseHistory("")
      body:throwAllCards()
      local mark = body:getTableMark("@[tshu__tianshu]")
      for name, _ in pairs(body.mark) do
        if not table.contains(nmark,name) then
          room:setPlayerMark(body, name, 0)
        end
      end
      body:clearPiles()
      body:reset()
      if body:getMark("tshujl__sajia") > 0 and body:usedSkillTimes("tshujl__matai", Player.HistoryGame) == 0 then
        return
      end
      body:setSkillUseHistory("")
      if  room:getBanner("@&GetGenerals") and #room:getBanner("@&GetGenerals") < 1   then 
        room:doBroadcastNotify("ShowToast", "备用将库为0，请等待队友补充将库")
        return
      end
      
      --[[
      local current = room.logic:getCurrentEvent()
      local last_event = nil
      if room.current.dead then
        last_event = current:findParent(GameEvent.Turn, true)
      end
      if last_event == nil then
        last_event = current
        if last_event.parent then
          repeat
            if table.contains({GameEvent.Round, GameEvent.Turn, GameEvent.Phase}, last_event.parent.event) then break end
            last_event = last_event.parent
          until (not last_event.parent)
        end
      end
      ]]
      changeGeneral(room)
    elseif event == fk.RoundStart and room:getTag("RoundCount") == 5  then
      room:doBroadcastNotify("ShowToast", "第五轮狂暴，所有玩家弃置区域内的所有牌")
      for _, p in ipairs(room.alive_players) do
        if p.role == "lord" or p.role == "loyalist" then
          p:throwAllCards("hej")
          p:throwAllCards("e")
          p:throwAllCards("h")
          p:throwAllCards("j")
        end
      end
    elseif event == fk.TurnStart and (player.role == "lord" or player.role == "loyalist") and room:getTag("RoundCount") >= 7  then
      room:doBroadcastNotify("ShowToast", "狂暴，第七轮起所有玩家回合开始时失去一点体力")
      room:loseHp(player,1,self.name)
    elseif event == fk.TurnStart and player.role == "rebel" then
      local A = room:getBanner("tshu-start") or 0
      local B = room:getBanner("tshu-cover") or 0
      if A > 0 and not player.dead then
        player:drawCards(A,self.name)
      end
      if B > 0 and not player.dead and player:isWounded() then
        player.room:recover({
          who = player,
          num = math.min(player:getLostHp(),B),
          recoverBy = player,
          skillName = self.name
          })
      end
    elseif event == fk.TurnEnd and player.role == "rebel" then
      local C = room:getBanner("tshu-finish") or 0
      if C > 0 and not player.dead then
        player:drawCards(C,self.name)
      end
    elseif event == fk.DamageCaused and player.role == "rebel" then
      local D = room:getBanner("tshu-damage") or 0
      if D > 0 then
        data.damage = data.damage + D
      end
    elseif event == fk.RoundEnd then
      changeGeneral(room)
      local n = 0
      for _, p in ipairs(room.alive_players) do
        if p.role == "lord" or p.role == "loyalist" then
          n = n + 1
        end
      end
      if n == 0 then
        room:doBroadcastNotify("ShowToast", Fk:translate("#tshu__lordwin"))
        room:gameOver("rebel")
      end
    end
  end,
}
local tshu_mode = fk.CreateGameMode{
  name = "tshu_mode",
  minPlayer = 3,
  maxPlayer = 10,
  rule = tshu_rule,
  logic = tshu_getLogic,
  surrender_func = function(self, playedTime)
    return { { text = "tshu_allcan", passed = true } }
  end,
  --[[
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner and p.role ~= "renegade" then
        return ""
      end
    end
    return winner
  end,]]
}

Fk:loadTranslationTable{
  ["tshu_mode"] = "无尽天书",
  ["tshu choose general"] = "我们支持自由选将",
  ["@&Allgenerals"] = "已抽武将",
  ["@getAllgenerals"] = "击杀武将数",
  ["tshu_allcan"] = "你随时都可以投降",
  ["@&GetGenerals"] = "所持武将",
  ["#tshu__get"] = "选择一个武将加入你的所持武将库",
  ["#tshu__change"] = "你可以更换一个武将",
  ["#tshu__lordwin"] = "很遗憾，你输了",
  ["#tshu__nolordwin"] = "斯国一，你打通了全部将池!",
  [":<font color='yellow'>更换武将</font>"] = "<font color='yellow'>从所持武将库中选择一个武将替换之，并触发武将牌上所有“游戏开始时”技能</font>"..
    "<br><font color='yellow'>(每5层重置换将次数。)</font>",
  [":保留武将"] = "保留现在的武将，无事发生;后续或死亡后仍可换将",
  ["tshu__change&"] = "换将",
  [":tshu__change&"] = "每5层限一次，出牌阶段，若你为正面你可更换主将并触发一次所有游戏开始时机的技能,然后你翻面",
  ["#tshu_rule"] = "无尽天书",
  ["@layers"] = "通关层数",
  ["@&godboss"] = "BOSS",
  ["@&tshu__jl"] = "将灵池",
  ["tshu__changejl&"] = "将灵",
  [":tshu__changejl&"] = "放生现在所持有的将灵，然后可以从【将灵池】中重新领养一只将灵。",
  ["tshu__store&"] = "商店",
  [":tshu__store&"] = "逛一逛“天书商店”。",
  ["tshu__ice&"] = "暂停",
  [":tshu__ice&"] = "不离开服务器的情况下，会进行无限询问的烧条，可供玩家暂时离开电脑执行一些其他操作。",
  ["@[tshu__tianshu]"] = "天书卷轴",
  ["tshu_prompt"] = "记载技能",
  ["tshujl__nianzhuge_choice"] = "诸葛亮",

  ["#tshu__addox"] = "展示手牌中一张【杀】【闪】【桃】【酒】【乐】来召唤偶像",

  ["@tshu_lv"] = "<font color='red'>荣耀</font>",
  ["tshu_draw1"] = "<font color='blue'>摸两张牌</font>",
  ["tshu_recover1"] = "<font color='green'>回一点血</font>",
  ["tshu_skill1"] = "<font color='yellow'>重置技能</font>",
  ["tshu_random1"] = "<font color='red'>盲盒奖励</font>",
  [":tshu_draw1"] = "<font color='blue'>从牌堆中摸俩张牌</font>",
  [":tshu_recover1"] = "<font color='green'>回复一点体力</font>",
  [":tshu_skill1"] = "<font color='yellow'>选择一个天书技能移除之，然后重新获得一个天书技能（不能选择限定技或觉醒技）</font>",
  [":tshu_random1"] = "<font color='red'>从可能好可能差可能无事发生的奖励中获得一个<br>要我说，为什么不选择【重置技能】呢？</font>",

  ["tshu_draw2"] = "<font color='blue'>摸至满牌</font>",
  ["tshu_recover2"] = "<font color='green'>回至满血</font>",
  ["tshu_skill2"] = "<font color='yellow'>重置技能</font>",
  ["tshu_random2"] = "<font color='red'>超级盲盒</font>",
  [":tshu_draw2"] = "<font color='blue'>将手牌摸至手牌上限（至少摸俩张）</font>",
  [":tshu_recover2"] = "<font color='green'>将体力回复至体力上限</font>",
  [":tshu_skill2"] = "<font color='yellow'>选择一个天书技能移除之，然后重新获得一个天书技能（包括限定技或觉醒技）</font>",
  [":tshu_random2"] = "<font color='red'>更好或更差的随机奖励；<br>别犹豫，直接选我!</font>",

  [":放弃奖励"] = "这次就先不要奖励了",
  [":复活"] = "浴火重生！从所持武将库中选一个武将来复活。",
  [":放弃"] = "武将库不够满意，还是继续让队友C吧。",
  ["@@easy"] = "体验模式",
  [":tshu_mode"] = desc_tshu,
  ["@[:]sday_qdian"] = "",
  ["sday_qdian"] = "<font color='red'>周六庆典</font>",
  [":sday_qdian"] = "于每周六开启的天书房间将会启用<font color='red'>天书庆典</font>"..
  "<br>天书庆典期间，所有角色于游戏开始时可从随机将灵中选择一个领养或替换。"..
  "<br>————————————————"..
  "<br><font color='red'><b>庆典将灵解锁方式</b></font><br>"..
  "<br><b><font color='red'>念·诸葛亮</font></b>：携带 <font color='red'>念·诸葛亮</font> 将灵在不换将、不死亡、不更换将灵且未存在真人玩家选择 <font color='black'>撒迦</font> 的情况下通过200层即可永久解锁 <font color='red'>念·诸葛亮</font> 。<br>"..
  "<br><b><font color='blue'>念·吕布</font></b>：解锁 <font color='red'>念·诸葛亮</font> 的玩家于 天书庆典增益 中可选择将灵 <font color='pink'>喵·吕玲绮</font> ，携带 <font color='pink'>喵·吕玲绮</font> 于整百层累计击杀五只天书诸神BOSS即可永久解锁 <font color='pink'>喵·吕玲绮</font> 与 <font color='blue'>念·吕布</font> 。<br>"..
  "<br><font color='yellow'>以上解锁内容仅限未开启副将按钮的正常模式</font>",

}

return tshu_mode
